Выполнение действий на основе скручивания в Objective-C - PullRequest
2 голосов
/ 13 мая 2011

Я пытаюсь добиться следующего в 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];

Ответы [ 3 ]

7 голосов
/ 13 мая 2011
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];

или отправьте асинхронный запрос с помощью

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

, посмотрите NSMutableURLRequest Ссылка на класс , чтобы увидеть, как установить что.

1 голос
/ 13 мая 2011

Вы можете использовать NSURLConnection для этого; вот образец:

Как сделать HTTP-запрос для получения объекта JSON в ответ на приложение iPhone?

Может быть способ действительно запустить скрипт curl, используя NSTask: http://borkware.com/quickies/one?topic=nstask

0 голосов
/ 24 октября 2012

Я много искал, чтобы преобразовать этот cUrl-запрос для отправки push-уведомлений Urban Airship. Наконец-то я сделал это ниже, это исходный код, который работал для меня: Обязательно: ASIHTTPRequest // Требуется для выполнения Http-запроса

+(void)sendUrbanAirshipPushWithPayload:(NSString *) payload
{
    //payload = @"{"aps": {"badge": 1, "alert": "The quick brown fox jumps over the lazy dog."}, "aliases": ["12345"]}";
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"https://go.urbanairship.com/api/push/"]];
    [request addRequestHeader:@"Content-Type" value:@"application/json"];
    [request setRequestMethod:@"POST"];
    //Set the HTTP Basic Authentication header with the application key as the username, and the master secret for the password
    [request setUsername:kUrbanAirshipKey];
    [request setPassword:kUrbanAirshipMasterSecret];
    [request setPostBody:[NSMutableData dataWithData:[payload dataUsingEncoding:NSUTF8StringEncoding]]];
    [request startSynchronous];
    if([request error])
    {
        NSLog(@"Code : %d, Error: %@",[[request error] code],[[request error] description]);
    }
    NSLog(@"Code: %d, Description: %@, Message: %@",[request responseStatusCode],[request responseData],[request responseStatusMessage]);

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...