异步获取数据而不是使用initWithContentsOfURL

Pra*_*oth 3 iphone asynchronous nsurl nsstring

我目前正在使用此代码从URL获取数据: NSURL *url = [[NSURL alloc] initWithString:urlstring]; NSString *stringfromFB = [[NSString alloc] initWithContentsOfURL:url];

我想知道如何异步收集这些数据,以便每次我需要执行此操作时我的应用程序都不会冻结.谢谢!

dan*_*anh 8

最简单的方法在os5中可用,如下所示:

NSString *stringfromFB;
NSURL *url = [[NSURL alloc] initWithString:urlstring];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (data) {
        stringfromFB = [[NSString alloc] initWithData:data
                                             encoding:NSUTF8StringEncoding];  // note the retain count here.
    } else {
        // handle error
    }
}];
Run Code Online (Sandbox Code Playgroud)

如果由于某种原因你被困在os <5中,你将需要开始与委托的连接,并实现如此处所示的委托协议(以及其他许多地方).