Does -dataWithContentsOfURL: of NSData work in a background thread?

﹥>﹥吖頭↗ 提交于 2019-11-29 07:06:52

问题


Does -dataWithContentsOfURL: of NSData work in a background thread?


回答1:


No, it doesn't.

In order to get data from URL asynchronously you should use the NSURLRequest and NSURLConnection approach.

You will have to implement the NSURLConnectionDelegate methods:

-(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;



回答2:


I'm using dataWithContentsOfURL in a background thread fine.

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

Call something like this from main thread.

[self performSelectorInBackground:@selector(loaddata) withObject:nil];

If you want to perform updates to ui at end of loaddata, be sure to call a function on main thread.




回答3:


No. You can use NSURLSession instead, though.

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];



回答4:


No, it blocks the current thread.

You need to use NSURLConnection in order to have asynchronous requests.




回答5:


Also you may use -dataWithContentsOfURL + NSOperation + NSOperationQueue




回答6:


I'm guessing this has changed a bit over the years. But, these days,

NSURLRequest* request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse* response, NSData* data, NSError* error) {
}];

will give you an async network call.




回答7:


No, this will block the thread and you will load the contents of file into the RAM. You can download content directly into file without temporary NSData to avoid huge RAM usage. Something like this solution https://stackoverflow.com/a/6215458/2937913



来源:https://stackoverflow.com/questions/3078765/does-datawithcontentsofurl-of-nsdata-work-in-a-background-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!