-dataWithContentsOfURL:NSData在后台线程中工作吗?

don*_*ile 13 iphone nsdata

-dataWithContentsOfURL:NSData在后台线程中工作吗?

Mic*_*ler 15

不,它没有.

为了从URL中异步获取数据,您应该使用NSURLRequestNSURLConnection方法.

您必须实现这些NSURLConnectionDelegate方法:

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
-(void)connectionDidFinishLoading:(NSURLConnection *)connection;
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
Run Code Online (Sandbox Code Playgroud)


Jon*_*nny 8

我在后台线程中使用dataWithContentsOfURL.

-(void)loaddata {
    NSData* data = [NSData dataWithContentsOfURL:@"some url"];
    if (data == nil) {
        DLog(@"Could not load data from url: %@", url);
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

从主线程调用这样的东西.

[self performSelectorInBackground:@selector(loaddata) withObject:nil];
Run Code Online (Sandbox Code Playgroud)

如果要在loaddata结束时对ui执行更新,请务必在主线程上调用函数.


小智 5

不过.但是,您可以使用NSURLSession.

NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];

NSString *imageURL = @"Direct link to your download";

NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];

NSURLSessionDownloadTask *getImageTask = [session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageURL]] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    dispatch_async(dispatch_get_main_queue(), ^{

        UIImage *downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
    });
}]; 
[getImageTask resume];
Run Code Online (Sandbox Code Playgroud)