iOS 9 起 NSURLConnection 標記為 deprecated,iOS 13 完全移除。新代碼必須使用 NSURLSession。
- (void)downloadWithURL:(NSURL *)url completion:(void (^)(NSData * _Nullable, NSError * _Nullable))completion {
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) { completion(nil, error); return; }
NSData *data = [NSData dataWithContentsOfURL:location];
completion(data, nil);
}];
[task resume];
}downloadTaskWithResumeData:。[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.app.bg"],App 被殺死也能繼續下載。NSURLSessionDownloadDelegate 的 URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:。NSURLConnection 替換為 NSURLSession。sendSynchronousRequest)改為異步 + 完成閉包/Delegate。NSAppTransportSecurity 允許 HTTP(或強制 HTTPS)。