2016-02-01 102 views

回答

12

此代碼:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; 
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; 
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 
    NSLog(@"File downloaded to: %@", filePath); 
}]; 
[downloadTask resume]; 

是在自述項目爲:https://github.com/AFNetworking/AFNetworking

3

我明白了原來的問題是在OBJ - C的,但是這出現在谷歌搜索,所以對於任何人否則絆倒後,它並和需要@Lou佛朗哥的回答雨燕版本,那就是:筆記

let configuration = URLSessionConfiguration.default 
let manager = AFURLSessionManager(sessionConfiguration: configuration) 
let url = URL(string: "http://example.com/download.zip")! // TODO: Don't just force unwrap, handle nil case 
let request = URLRequest(url: url) 

let downloadTask = manager.downloadTask(
    with: request, 
    progress: { (progress: Progress) in 
        print("Downloading... progress: \(String(describing: progress))") 
       }, 

    destination: { (targetPath: URL, response: URLResponse) -> URL in 
        // TODO: Don't just force try, add a `catch` block 
        let documentsDirectoryURL = try! FileManager.default.url(for: .documentDirectory, 
                      in: .userDomainMask, 
                      appropriateFor: nil, 
                      create: false) 

        return documentsDirectoryURL.appendingPathComponent(response.suggestedFilename!) // TODO: Don't just force unwrap, handle nil case 
       }, 

    completionHandler: { (response: URLResponse, filePath: URL?, error: Error?) in 
          print("File downloaded to \(String(describing: filePath))") 
         } 
) 

downloadTask.resume() 

夫婦在這裏:

  • 這是夫特3/4斯威夫特
  • 我添加了一個progress閉合以及(只是一個print語句)。但當然,在原來的例子中,通過nil是完全正確的。
  • 有三個地方(標記爲TODO:)沒有錯誤處理的地方可能會失敗。顯然你應該處理這些錯誤,而不是隻是崩潰。
+0

謝謝。它完美的作品 –

+0

非常感謝很多人,工作良好與迅速 - 4也 –

相關問題