Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

ios - Executing curl based actions in Objective-C

I am trying to achieve the following in Objective-C:

curl -X POST -u "<application key>:<master secret>" 
    -H "Content-Type: application/json" 
    --data '{"aps": {"badge": 1, "alert": "The quick brown fox jumps over the lazy dog."}, "aliases": ["12345"]}' 
    https://go.urbanairship.com/api/push/

Is there some sort of library I can use that achieves this? Obviously I have all of the values ready to go ahead and make my request, but I'm not exactly sure how to do it in Objective-C.

I am using TouchJSON, however I'm not quite sure how to construct the correct JSON payload above and POST this to the server (also I'd prefer this to be an asynchronous request rather than a synchronous).

NSError *theError = NULL;

NSArray *keys = [NSArray arrayWithObjects:@"aps", @"badge", @"alert", @"aliases", nil];
NSArray *objects = [NSArray arrayWithObjects:?, ?, ?, ?, nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSURL *theURL = [NSURL URLWithString:@"https://go.urbanairship.com/api/push/"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
[theRequest setHTTPMethod:@"POST"];

[theRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSData *theBodyData = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary error:&theError];
[theRequest setHTTPBody:theBodyData];

NSURLResponse *theResponse = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSDictionary *theResponseDictionary = [[CJSONDeserializer deserializer] deserialize:theResponseData error:&theError];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
NSURL *url = [NSURL URLWithString:@"https://go.urbanairship.com/api/push/"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:@"POST"];
//... set everything else
NSData *res = [NSURLConnection  sendSynchronousRequest:req returningResponse:NULL error:NULL];

or send asynchronous request with

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:some];

have a look at NSMutableURLRequest Class Reference to see how to set what.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...