首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

iOS 9+ 網絡請求遷移:從 NSURLConnection 到 NSURLSession 的異步下載最佳實踐

     編輯:程式設計疑難解答

棄用背景

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:。

遷移清單

  1. 全局搜索 NSURLConnection 替換為 NSURLSession。
  2. 同步請求(sendSynchronousRequest)改為異步 + 完成閉包/Delegate。
  3. 配置 NSAppTransportSecurity 允許 HTTP(或強制 HTTPS)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved