ios - 使用 Swift 以不同名称保存文件

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

最佳答案

这里是使用您指定的名称将您的数据保存到DocumentDirectory中的实用函数。该方法有一个回调,它会在执行保存操作后调用,它将返回图像保存在目录中的路径。该函数用 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)

            }
       }

}

谢谢。

关于ios - 使用 Swift 以不同名称保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43798452/

相关文章:

ios - 如何在底部的每个屏幕中显示 View

ios - 适用于 iOS 的 Dropbox SDK 在模拟器上运行,而不是在实际设备上运行

objective-c - 谓词适用于数组,但不适用于fetchRequest

ios - Facebook 权限请求导致 iOS 应用程序崩溃

ios - 将字符串从 iPhone 发送到 WatchKit 应用程序

ios - 无法在包 Xcode8 中加载 NIB

objective-c - iPhone 中的线性条码生成

ios - Swift 3 中的实时搜索限制

arrays - 我应该如何获取作为 Int 通过测试的对象的最后一个索引?

ios - 从 Swift 中的数据模型返回更具体的对象