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

时间:2014-11-25 14:20:25

标签: ios swift

我正在尝试为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目录中。

我尝试在完成下载操作(didFinishDownloadingToURL方法)后将此文件移动到Document目录。但是我在这里遇到问题。问题是文件名。就像那个“CFNetworkDownload_qsmwsB.tmp”并且在下载完成的文件后它没有改变为原始名称。(文件名必须是“myBook.pdf”)因此我看到“.tmp”文件在iTunes中

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

1 个答案:

答案 0 :(得分:4)

我认为您所寻找的是downloadTask.originalRequest.URL.lastPathComponent,它会为您提供网址中提供的原始文件名。

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

    }

}