gpt4 book ai didi

ios - 如何使用 NSURLSession 下载多个文件

转载 作者:行者123 更新时间:2023-11-30 13:28:23 25 4
gpt4 key购买 nike

我有一个问题。我正在尝试使用 NSURLSession 进行多次下载,但我没有明白我做错了什么?该类在类 X 中初始化一次。startDownload(realm.objects(Music)[indexPath.row]) 可以在同一个类中调用多次。 “下载”类中存在问题,我确信这一点。如果您需要更多信息,请写信

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

}

谢谢

最佳答案

首先,不要这样做。让 session 为您限制并发数。只需立即向其抛出所有请求即可。

其次,除非您的应用程序刚刚启动,否则不要重新创建后台 session 配置。您应该只创建一次,并且永远不要再创建它。多个 NSURLSession 对象指向同一标识符的行为是,IIRC,未定义。

第三,在完成 session 之前不要使 session 无效。第一个请求完成后,您将取消所有未完成的请求。

第四,除非您想停止正在进行的任务,否则您不应该取消任务。如果任务已经完成,取消它不会执行任何操作。

除此之外,我同意那些人的说法,即您需要先解释一下代码出了什么问题,然后我才能提供进一步的帮助。 :-)

关于ios - 如何使用 NSURLSession 下载多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36864679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com