我想實現在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/
是否有某種庫我可以使用實現這個?很顯然,我已經準備好了所有的價值觀並提出了我的要求,但我並不確定如何在Objective-C中做到這一點。
我正在使用TouchJSON,但我不太清楚如何構建正確的JSON負載,並將其發佈到服務器(也是我更喜歡這是一個異步請求,而不是同步)。
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];
正是。同樣使用'sendSynchronousRequest:returningResponse:'很少是一個好主意。如果你最後想要一個可用的應用程序,你應該使用異步方法調用'NSURLConnection'。 – toto 2011-05-13 12:43:59
@toto:+1編輯了我的答案。但總是取決於請求時間以及您的應用會是什麼樣子,即,如果它能夠在沒有響應的情況下工作。 – 2011-05-13 12:45:00
@toto:我會說在受控後臺線程中使用'sendSynchronousRequest:returningResponse:'(從不主線程)*實際上會導致更容易測試,維護和擴展的代碼。 – PeyloW 2011-05-13 14:59:28