2016-04-26 25 views
0

Ich habe ein Problem. Ich versuche, mehrere Downloads mit NSURLSession zu machen, aber ich habe nicht verstanden, was ich falsch mache? Diese Klasse wird einmal in Klasse X initialisiert. StartDownload (realm.objects (Musik) [indexPath.row]) kann mehrmals in derselben Klasse aufgerufen werden. Probleme in der Klasse 'Download', das weiß ich sicher. Wenn Sie weitere Informationen benötigen, schreiben Sie bitteSo laden Sie mehrere Dateien mit NSURLSession

class Download: NSObject, NSURLSessionDelegate { 
var progress: Float = 0.0 
var progressBar: UIProgressView? 
var addButton: UIButton? 


private var downloadTask: [NSURLSessionDownloadTask] = [] 
private var backgroundSession: [NSURLSession] = [] 
private let realm = try! Realm() 

private var downloadObject:[Music] = [] 
private var queueObjects:[Music] = [] 


func startDownload(object: Music? = nil) { 
    if (object != nil) { 
     self.queueObjects.append(object!) 
    } 
    let url = queueObjects[queueObjects.startIndex].url 

    if downloadTask.count < 3 { 
     let backgroundSessionConfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("backgroundSession"+String(queueObjects.count)) 
     backgroundSession.append(NSURLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())) 
     let sessionIndex = backgroundSession.endIndex-1 
     backgroundSession[sessionIndex].sessionDescription = String(sessionIndex) 

     downloadTask.append(backgroundSession[sessionIndex].downloadTaskWithURL(NSURL(string: url)!)) 
     let taskIndex = downloadTask.endIndex-1 
     downloadTask[taskIndex].taskDescription = String(taskIndex) 
     downloadTask[taskIndex].resume() 

     downloadObject.append(queueObjects[queueObjects.startIndex]) 
     queueObjects.removeAtIndex(queueObjects.startIndex) 
    } 
} 

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { 

    let index = Int(downloadTask.taskDescription!)! 
    print("Index "+String(index)) 
    let range = downloadObject[ index ].url.rangeOfString("?")!.startIndex.advancedBy(0) 
    let url = downloadObject[ index ].url[downloadObject[index].url.startIndex..<range] 
    let theFileName = (url as NSString).lastPathComponent 
    let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) 
    let directoryPath:String = path[0] 
    let fileManager = NSFileManager() 
    let destinationURLForFile = NSURL(fileURLWithPath: directoryPath.stringByAppendingString("/"+theFileName)) 

    if fileManager.fileExistsAtPath(destinationURLForFile.path!){ 
     print(destinationURLForFile.path!) 
     saveObject(downloadObject[index], path: destinationURLForFile.path!) 
    } 
    else{ 
     do { 
      try fileManager.moveItemAtURL(location, toURL: destinationURLForFile) 
      print(destinationURLForFile.path!) 
      saveObject(downloadObject[index], path: destinationURLForFile.path!) 
     } catch { 
      print("An error occurred while moving file to destination url") 
     } 
    } 
    if addButton != nil { 
     addButton?.hidden = true 
    } 
    downloadTask.cancel() 
    session.invalidateAndCancel() 

    self.backgroundSession[Int(session.sessionDescription!)!].invalidateAndCancel() 
    self.backgroundSession.removeAtIndex(Int(session.sessionDescription!)!) 
    self.downloadTask[Int(downloadTask.taskDescription!)!].cancel() 
    self.downloadTask.removeAtIndex(Int(downloadTask.taskDescription!)!) 
} 

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { 
    progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite) 
    if progressBar != nil { 
     progressBar?.progress = progress 
    } 
} 

private func saveObject(object: Music, path: String) { 
    let downloadMusic = DownloadMusic() 
    downloadMusic.id = object.id 
    downloadMusic.owner_id = object.owner_id 
    downloadMusic.artist = object.artist 
    downloadMusic.title = object.title 
    downloadMusic.duration = object.duration 
    downloadMusic.path = path 

    try! realm.write() { 
     realm.add(downloadMusic) 
     downloadObject.removeAtIndex(downloadObject.endIndex-1) 
     if self.queueObjects.count > 0 { 
      self.startDownload() 
     } 
     print(queueObjects.count) 
     print(downloadObject.count) 
     print(downloadMusic) 
    } 
} 

}

Danke

+0

Es ist wirklich schwer, mehrere Seiten Code zu debuggen, nur indem Sie es betrachten, wenn Sie nicht einmal wissen, wie es sich verhält, wenn es ausgeführt wird. Was macht dieser Code, den Sie nicht erwarten? Bitte beschreiben Sie detailliert, wie sich das Verhalten verhält und wie sich dieses Verhalten von dem unterscheidet, was Sie erwarten. –

Antwort

0

Zuerst nicht, dass das so tun. Lassen Sie die Sitzung die Nebenläufigkeit für Sie begrenzen. Werfen Sie alle Anfragen sofort an.

Zweitens, erstellen Sie keine Hintergrundsitzungskonfiguration neu, es sei denn, Ihre App wurde gerade gestartet. Sie sollten es genau einmal und nie wieder erstellen. Das Verhalten mehrerer NSURLSession-Objekte, die auf denselben Bezeichner zeigen, ist IIRC undefiniert.

Drittens, machen Sie die Sitzung erst ungültig, wenn Sie damit fertig sind. Sie stornieren alle ausstehenden Anfragen, sobald die erste abgeschlossen ist.

Viertens sollten Sie die Aufgaben nicht abbrechen, es sei denn, Sie möchten eine laufende Aufgabe stoppen. Wenn eine Aufgabe bereits beendet wurde, führt das Abbrechen zu nichts.

Darüber hinaus werde ich den Leuten zustimmen, die sagten, dass Sie erklären müssen, was der Code falsch macht, bevor ich weiter helfen kann. :-)

Verwandte Themen