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

时间:2012-03-23 23:43:08

标签: iphone asynchronous nsstring nsurl

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

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

5 个答案:

答案 0 :(得分: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
    }
}];

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

答案 1 :(得分:4)

您可以使用GCD:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    NSURL *url = [[NSURL alloc] initWithString:urlstring]; 
    NSString *stringfromFB = [[NSString alloc] initWithContentsOfURL:url]
});

答案 2 :(得分:0)

如果您不想等待连接完成加载网址,可以使用NSURLConnection异步加载。

[NSURLConnection connectionWithRequest:
  [NSURLRequest requestWithURL:
  [NSURL URLWithString:yourUrlString]]
   delegate:self];

答案 3 :(得分:0)

// Do not alloc init URL obj. for local use.
NSString *urlString = @"put your url string here";

NSURL *url = [NSURL URLWithString:urlString];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 

上面的委托方法是NSURLConnectionDelegate,你需要处理所有的事情,如响应错误等。默认情况下提供它,所以我们可以直接覆盖它而不用

我在我的项目中使用过一次它将适用于异步请求但是如果你收到的图像数量也是如此,那么还要使用 IconDownloader EGOImageView 来实现延迟加载图像和冻结应用程序的机会很低。

答案 4 :(得分:0)

现在不推荐使用NSURLConnection,您需要使用NSURLSession。

NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *task = [session dataTaskWithRequest: request
                                        completionHandler: ^(NSData *data, NSURLResponse *response, NSError *networkError) {

            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

            if ([httpResponse statusCode] == STATUS_OK) {
                // use data                     
            }
            else {
                NSLog(@"Network Session Error: %@", [networkError localizedFailureReason]);
            }
}];

[task resume];