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

前端 未结 7 1484
南笙
南笙 2020-12-30 05:39

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

7条回答
  •  旧巷少年郎
    2020-12-30 06:18

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

提交回复
热议问题