使用Swift保存具有不同名称的文件

时间:2017-05-05 06:58:18

标签: ios swift swift3 alamofire nsfilemanager

我正在使用Alamofire从服务器下载文件。但我想以不同的方式命名它,就像我们从网上下载文件一样,并且可以按照我们的意愿命名,同样如何在swift中实现

我使用以下代码: -

Alamofire.download(fileUrl, to: destination)
        .downloadProgress { progress in
            print("Download Progress:---------- \   
        (progress.fractionCompleted)")


        }
        .responseData { response in

            print(response.request)
            print(response.response)
            print(response.temporaryURL)
            print(response.destinationURL)
            print(response.error)

    }

不希望使用alamofire重命名或覆盖文件。还有其他方法

1 个答案:

答案 0 :(得分:0)

以下是将您的Data保存到 DocumentDirectory 并使用您提供的名称的实用功能。此方法有一个call back,它将在执行保存操作后调用,它将返回图像保存在目录中的路径。此函数用Swift 3

编写
func saveImageInDocDirectory(data: Data?, fileName: String?, successblock: @escaping (_ path: String?) -> Void) { // To add the image to cache for given identifier.

    let paths = NSSearchPathForDirectoriesInDomains( .documentDirectory, .userDomainMask, true)[0] as String
    let path = paths.appending("/\(fileName!)")
    if !FileManager.default.fileExists(atPath: path) {
        do {
            try FileManager.default.createDirectory(at: URL(fileURLWithPath: path), withIntermediateDirectories: false, attributes: nil)
        } catch {
            print("Error creating images folder in Cache dir: \(error)")
        }
    }

    if (filemgr.fileExists(atPath: path)) {
        try! filemgr.removeItem(atPath: path)
    } else {
        do {
            try data?.write(to: URL(fileURLWithPath: path, isDirectory: false))
            successblock(path)
        } catch {
            successblock(nil)
            print("Error while caching the data in cache folder.")
        }
    }

}

您可以将此方法称为

Alamofire.download(fileUrl, to: destination)
    .downloadProgress { progress in
        print("Download Progress:---------- \   
    (progress.fractionCompleted)")


    }
    .responseData { response in

        print(response.request)
        print(response.response)
        print(response.temporaryURL)
        print(response.destinationURL)
        print(response.error)
       if let data = response.result.value {
         self.saveImageInDocDirectory(data: data, fileName: "YourFile",  successblock: { (path) in

                print(path)

            }
       }

}

感谢。

相关问题