2016-02-01 19 views

risposta

12

Questo codice:

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

è sul README per il progetto: https://github.com/AFNetworking/AFNetworking

3

mi rendo conto la questione originale è in Obj-C, ma questo viene in su in una ricerca su Google, quindi per chiunque altro inciampo su di esso e e che necessitano la versione Swift della risposta di Franco @Lou, eccolo:

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

paio di note qui:

012.
  • Si tratta di Swift 3/Swift 4
  • ho aggiunto una chiusura progress pure (solo una dichiarazione print). Ma ovviamente è perfettamente accettabile passare nil come nell'esempio originale.
  • Ci sono tre posizioni (contrassegnate con TODO:) senza la gestione degli errori in cui le cose potrebbero fallire. Ovviamente dovresti gestire questi errori, invece di andare in crash.
+0

grazie. funziona perfettamente –

+0

grazie mille, funziona bene con swift - 4 anche –

Problemi correlati