IPHONE JSON 另一个例子

    // Send an asyncronous request on the queue     [NSURLConnectionsendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse*response, NSData *data, NSError *error) {                 // If there was an error getting the data         if (error) {                         dispatch_async(dispatch_get_main_queue(), ^(void) {                 completionBlock(nil, error);             });             return;         }                 // Decode the data         NSError *jsonError;         NSDictionary*responseDict = [NSJSONSerialization JSONObjectWithData:data options:0error:&jsonError];                 // If there was an error decoding the JSON         if (jsonError) {                         dispatch_async(dispatch_get_main_queue(),^(void) {                             });             return;         }                 // All looks fine, lets call the completion block with the response data         dispatch_async(dispatch_get_main_queue(), ^(void) {             completionBlock(responseDict, nil);         });     }]; }
RAW

So, I am working on a little app that front an API back-end I am also writing and have been watching the WWDC 2011 videos on GCD and Blocks... thought I would give all this a go!

It's pretty simple, heres an example request:

[SHAPIController performRequestWithUri:@"/your/api/method"params:nil completionHandler:^(NSDictionary *response,NSError *error) {             if (error) {                NSLog(@"%@", error);             }            NSLog(@"%@", response);         }];
RAW

The second NSLog will output something like this (of course depending on the API):

{     some = json;     yeah =     (         yeah,         sdfsdf,         sdfdsf     ); }
RAW

The completion block will always be called on the main thread so you can update your UI or whatever there.

Hope its useful to someone :)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值