繁体   English   中英

使用Swift保存其他名称的文件

[英]Save file with different name using Swift

我正在使用Alamofire从服务器下载文件。 但是我想用不同的方式命名它,就像我们从网络上下载文件一样,并可以根据需要命名,同样,如何迅速

我正在使用以下代码:-

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重命名或覆盖文件。 还有其他方法吗

这是动手操作的功能,可以使用您提供的名称将Data保存到DocumentDirectory中 此方法有一个call back ,该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)

            }
       }

}

谢谢。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM