下载并保存文件并保留相同的文件名

时间:2015-04-02 17:39:03

标签: xcode swift nsurlconnection

我正在尝试使用NSURLConnection代理下载我的网络服务器上存在的.mp3文件。 我的问题是如何在DocumentDirectory中保留相同的文件名及其扩展名(.mp3)而不重命名?

以下是我在connectionDidFinishLoading中所做的,但不完整。

func connectionDidFinishLoading(connection: NSURLConnection!) {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] as String
    let filePath = documentsDirectory.stringByAppendingPathComponent("AudioFiles")

    self.songData.writeToFile(filePath, atomically: true)

}

由于

1 个答案:

答案 0 :(得分:0)

你可以这样做

func connectionDidFinishLoading(connection: NSURLConnection!) {

    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] as String

    let description = connection.description()
    var descriptionArr = split(description){$0 == "/"}
    let descriptionArrCount = countElements(description)
    if descriptionArrCount == 0
    {
         return
    }
    let fileName = description[descriptionArrCount - 1] as String        

    let filePath = documentsDirectory.stringByAppendingPathComponent(fileName)

    self.songData.writeToFile(filePath, atomically: true)

}