9

Se creo un NSURLSessionDownloadTask e successivamente lo annullo prima che venga completato, il blocco di completamento continua a essere attivato.Come si gestisce un NSURLSessionTask annullato nel blocco del gestore di completamento?

let downloadTask = session.downloadTaskWithURL(URL, completionHandler: { location, response, error in 
    ... 
} 

Come posso verificare se l'attività di download è stato annullato in questo blocco in modo che io non cerco di operare sul download risultante quando non ce n'è uno?

risposta

23

Per un'attività di download, il gestore di completamento verrà chiamato con nil valore per il location e il valore code dell'oggetto NSError sarà NSURLErrorCancelled. In Swift 3:

let task = session.downloadTask(with: url) { location, response, error in 
    if let error = error as? NSError { 
     if error.code == NSURLErrorCancelled { 
      // canceled 
     } else { 
      // some other error 
     } 
     return 
    } 

    // proceed to move file at `location` to somewhere more permanent 
} 
task.resume() 

O a Swift 2:

let task = session.downloadTaskWithURL(url) { location, response, error in 
    if let error = error { 
     if error.code == NSURLErrorCancelled { 
      // canceled 
     } else { 
      // some other error 
     } 
     return 
    } 

    // proceed to move file at `location` to somewhere more permanent 
} 
task.resume() 

Allo stesso modo per le attività di dati, il gestore di completamento sarà chiamato con un Error/NSError che indica se è stato annullato. In Swift 3:

let task = session.dataTask(with: url) { data, response, error in 
    if let error = error as? NSError { 
     if error.code == NSURLErrorCancelled { 
      // canceled 
     } else { 
      // some other error 
     } 
     return 
    } 

    // proceed to move file at `location` to somewhere more permanent 
} 
task.resume() 

O a Swift 2:

let task = session.dataTaskWithURL(url) { data, response, error in 
    if let error = error { 
     if error.code == NSURLErrorCancelled { 
      // canceled 
     } else { 
      // some other error 
     } 
     return 
    } 

    // otherwise handler data here 
} 
task.resume() 
+0

Che dire per un'attività di download? La posizione sarà nulla? O dovrei semplicemente dipendere dall'errore? –

+0

Sì, il 'location' sarà' nil', ma puoi semplicemente controllare 'error', e se il' code' è 'NSURLErrorCancelled', sai che è stato cancellato per un motivo o per un altro. – Rob