2016-04-26 36 views
0

問題があります。私はNSURLSessionを使って複数のダウンロードをしようとしていますが、私が間違っていることはありませんでしたか?このクラスはクラスXで1回初期化されます。同じクラスで何度もstartDownload(realm.objects(Music)[indexPath.row])を呼び出すことができます。クラス「ダウンロード」の問題は、確かに分かります。あなたは、さらに情報が必要な場合は、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) 
    } 
} 

}

を書いてください

+0

実行時にどのように動作するかわからなくても、数ページのコードをデバッグするのは本当に難しいです。あなたが期待していないこのコードは何をしていますか?具体的にどのように動作するのか、どのようにその動作が期待どおりに異なるのかを記述してください。 –

答えて

0

まずありがとう、それをそのようにはしません。セッションで並行性が制限されるようにします。すべてのリクエストをただちに投げてください。

第2に、アプリが起動していない限り、バックグラウンドセッションの設定を再作成しないでください。あなたはそれを正確に一度だけ作り直すべきです。同じ識別子を指す複数のNSURLSessionオブジェクトの動作は、IIRCです。

第3に、セッションが終了するまでセッションを無効にしないでください。未処理のリクエストはすべて、最初のリクエストが完了するとすぐにキャンセルされます。

第4に、進行中のタスクを停止しない限り、タスクをキャンセルしないでください。タスクが既に終了している場合は、それをキャンセルすることは何もしません。

それを超えて、私はさらに助けになる前にコードが間違っていることを説明する必要があると言った人々に同意するつもりです。 :-)

関連する問題