我有这个代码:
struct ServerConnect {
enum Result<T> {
case succes(T)
case error(String)
}
typealias completionHandler = (Result<Data >) -> ()
func getJsonFromServer(parameters: String, completion: @escaping completionHandler) {
let fullUrlString = ApiConstans.fullPath + parameters
guard let url = URL(string: fullUrlString) else {
debugPrint("\(ErrorsLabels.ServerConnect01)")
return completion(.error("\(ErrorsLabels.ServerConnect01)"))
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard error == nil else {
debugPrint("\(ErrorsLabels.ServerConnect02)")
return completion(.error("\(ErrorsLabels.ServerConnect02)"))
}
guard let data = data else {
debugPrint("\(ErrorsLabels.ServerConnect03)")
return completion(.error("\(ErrorsLabels.ServerConnect03)"))
}
debugPrint("R> \(fullUrlString)")
return completion(.succes(data))
}.resume()
}
func getJsonProducts(lang: String?, region: Int?, completion: @escaping completionHandler) {
self.getJsonFromServer(parameters: "?action=GET_PRODUCTS&lang=\(lang!)®ion=\(region!)", completion: completion)
}
}
我想将从互联网下载的数据保存在设备的内存中。
我正在尝试这段代码:
getJsonProducts(lang: selectedLanguage, region: selectedRegion , completion: { (data) in
print("@@@@@ \(data)")
saveJsonFileToTheDisk(path: selectedLanguage + "/json/products.json", downloadData: data)
})
func saveJsonFileToTheDisk(path: String, downloadData: Data){
do {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent(path)
try downloadData.write(to: fileURL, options: .atomic)
} catch { }
}
但不幸的是,它不起作用。我怎样才能让它发挥作用?
以下是错误:
Cannot convert value of type 'ServerConnect.Result' to expected argument type 'Data'
根据getJsonProducts
方法的定义:
func getJsonProducts(lang: String?, region: Int?, completion: @escaping (Result<Data>) -> ()) {
发送到completion
block 的参数data
实际上是包含数据的Result
类型,而不是数据本身。因此,您应该这样做:
getJsonProducts(lang: selectedLanguage, region: selectedRegion, completion: { result in
switch result {
case .succes(let data):
saveJsonFileToTheDisk(path: selectedLanguage + "/json/products.json", downloadData: data)
case .error(let errorMessage):
// Do something with the error message.
break
}
})
关于ios - 如何将从 Internet 下载的数据保存到内部设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50445705/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |