异步JSON请求目标C

JKX

我正在开发我的第一个iPhone应用程序,并且正在调用API以返回一些JSON,这些JSON填充了UI的不同元素。目前,我已经在helper类中实现了一个同步方法,该类在viewDidLoad方法中调用。

-(NSDictionary*) dataRequest: (NSString*)url withMethod:(NSString*)method
{

NSError *e;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:method];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData: requestHandler options: NSJSONReadingMutableContainers error: &e];
return json;

}

这里的问题是我锁定了我的UI,我尝试异步实现了这一点,但是在代码尝试填充UI元素很久之后才返回数据,这是实现异步调用并用正确的UI元素填充的最佳和正确方法数据?

姓名

预期在发出请求后很长时间(相对于发送请求后下一行代码几乎是瞬时执行的时间),数据将返回很长时间。诀窍是将UI的更新推迟到请求完成之前。

// optionally update the UI to say 'busy', e.g. placeholders or activity
// indicators in parts that are incomplete until the response arrives
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    // optionally update the UI to say 'done'
    if (!error) {
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData: requestHandler options: NSJSONReadingMutableContainers error: &e];
        // update the UI here (and only here to the extent it depends on the json)
    } else {
        // update the UI to indicate error
    }
}];

甚至更抽象-更正确-考虑到所获取的数据很可能是应用程序模型的一部分。从服务器获取数据只是更改模型的一个原因。当模型由于任何原因(通过用户操作或此访存或其他事件)发生更改时,视图控制器的工作就是观察模型是否发生更改,并告诉视图进行更新。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章