Ios 在Swift中完成下载后设置文件名

Ios 在Swift中完成下载后设置文件名,ios,swift,Ios,Swift,我正在尝试为iPhone开发下载管理器应用程序。我正在使用此类进行下载操作: import UIKit import Foundation typealias CompleteHandlerBlock = () -> () class newDownloadObject: NSObject,NSURLSessionDelegate, NSURLSessionDownloadDelegate { var session: NSURLSession! var handler

我正在尝试为iPhone开发下载管理器应用程序。我正在使用此类进行下载操作:

import UIKit
import Foundation

typealias CompleteHandlerBlock = () -> ()

class newDownloadObject: NSObject,NSURLSessionDelegate, NSURLSessionDownloadDelegate {
    var session: NSURLSession!
    var handlerQueue: [String : CompleteHandlerBlock]!

    class var sharedInstance: newDownloadObject {
        struct Static {
            static var instance : newDownloadObject?
            static var token : dispatch_once_t = 0
        }

        dispatch_once(&Static.token) {
            Static.instance = newDownloadObject()
            Static.instance!.handlerQueue = [String : CompleteHandlerBlock]()
        }

        return Static.instance!
    }

    //MARK: session delegate
    func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
        println("session error: \(error?.localizedDescription).")
    }

    func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
        completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust))
    }

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {        
        println("session \(session) has finished the download task \(downloadTask) of URL \(location).")
    }

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        println("session \(session) download task \(downloadTask) wrote an additional \(bytesWritten) bytes (total \(totalBytesWritten) bytes) out of an expected \(totalBytesExpectedToWrite) bytes.")

    }

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
        println("session \(session) download task \(downloadTask) resumed at offset \(fileOffset) bytes out of an expected \(expectedTotalBytes) bytes.")
    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        if error == nil {
            println("session \(session) download completed")
        } else {
            println("session \(session) download failed with error \(error?.localizedDescription)")
        }
    }
    func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
        println("background session \(session) finished events.")  
        if !session.configuration.identifier.isEmpty {
            callCompletionHandlerForSession(session.configuration.identifier)
        }
    }

    //MARK: completion handler
    func addCompletionHandler(handler: CompleteHandlerBlock, identifier: String) {
        handlerQueue[identifier] = handler
    }

    func callCompletionHandlerForSession(identifier: String!) {
        if(identifier == nil){
            return
        }
        var handler : CompleteHandlerBlock = handlerQueue[identifier]!
        handlerQueue!.removeValueForKey(identifier)
        handler()
    }
}
这很好,但我想访问从itunes下载的文件。因此,此文件必须位于Documents目录中

我尝试在完成下载操作(
didfishdownloadingtourl
方法)后将此文件移动到文档目录。但我在这里遇到了问题。问题是文件名。这就像“CFNetworkDownload_qsmwsB.tmp”一样,下载完成的文件后,它不会更改为原始名称。(文件名必须是“myBook.pdf”),因此我在iTunes中看到了“.tmp”文件


如何将文件直接下载到文档目录,或者如何在下载完成后更改文件名?

我想知道的是
downloadTask.originalRequest.URL.lastPathComponent
,它提供URL中提供的原始文件名

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
    println("session \(session) has finished the download task \(downloadTask) of URL \(location).")



    var error : NSError?
    var fileManager = NSFileManager()

    // this can be a class variable
    var docDirectoryURL = NSURL(fileURLWithPath: "/someDirectory/")

    // Get the original file name from the original request.
    var destinationFilename = downloadTask.originalRequest.URL.lastPathComponent
    // append that to your base directory
    var destinationURL =  docDirectoryURL?.URLByAppendingPathComponent(destinationFilename)

    /* check if the file exists, if so remove it. */
    if let path = destinationURL?.path {
        if fileManager.fileExistsAtPath(path) {
            fileManager.removeItemAtURL(destinationURL!, error: nil);
        }
    }
    /*copy from the temp location to the final location*/
    var success = fileManager.copyItemAtURL(location, toURL: destinationURL!, error: &error)

    if (!success) {
        if let actualError = error {
            println("An Error Occurred: \(actualError)")
        }

    }

}

我想你要找的是downloadTask.originalRequest.URL.lastPathComponent,它提供了URL中提供的原始文件名

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
    println("session \(session) has finished the download task \(downloadTask) of URL \(location).")



    var error : NSError?
    var fileManager = NSFileManager()

    // this can be a class variable
    var docDirectoryURL = NSURL(fileURLWithPath: "/someDirectory/")

    // Get the original file name from the original request.
    var destinationFilename = downloadTask.originalRequest.URL.lastPathComponent
    // append that to your base directory
    var destinationURL =  docDirectoryURL?.URLByAppendingPathComponent(destinationFilename)

    /* check if the file exists, if so remove it. */
    if let path = destinationURL?.path {
        if fileManager.fileExistsAtPath(path) {
            fileManager.removeItemAtURL(destinationURL!, error: nil);
        }
    }
    /*copy from the temp location to the final location*/
    var success = fileManager.copyItemAtURL(location, toURL: destinationURL!, error: &error)

    if (!success) {
        if let actualError = error {
            println("An Error Occurred: \(actualError)")
        }

    }

}

谢谢,我有类似的代码。但是文件名不是常量。如何从nsurlSession的方法获取文件名。我的意思是我发送这个包含下载链接的类字符串数组。它为每个链接创建线程并开始下载。完成下载后,它会将CFNetworkDownload_randomSomething.tmp作为名称。谢谢,我有类似的代码。但是文件名不是常量。如何从nsurlSession的方法获取文件名。我的意思是我发送这个包含下载链接的类字符串数组。它为每个链接创建线程并开始下载。完成下载后,它会将CFNetworkDownload_randomSomething.tmp作为名称。