在Objective-C中执行基于curl的操作

fuz*_*uzz 2 curl objective-c ios

我试图在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/
Run Code Online (Sandbox Code Playgroud)

是否有某种我可以使用的库来实现这一目标?很明显,我已经准备好了所有的价值观并提出我的要求,但我不确定如何在Objective-C中做到这一点.

我正在使用TouchJSON,但是我不太确定如何在上面构造正确的JSON有效负载并将其POST到服务器(我更喜欢这是异步请求而不是同步).

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];
Run Code Online (Sandbox Code Playgroud)

Kai*_*ann 7

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];
Run Code Online (Sandbox Code Playgroud)

或发送异步请求

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:some];
Run Code Online (Sandbox Code Playgroud)

看看NSMutableURLRequest类参考,看看如何设置.

  • 究竟.使用`sendSynchronousRequest:returningResponse:`也不是一个好主意.如果你想在最后拥有一个可用的应用程序,你应该使用async方法调用`NSURLConnection`. (5认同)