我正在尝试从远程位置下载plist文件,并在我正在创建的iOS应用中使用它。该文件将用于应用程序日历中的日历详细信息。显然,我可以更新远程文件,而不必在每次需要更改日历详细信息时将更新推送到应用程序本身。
我开始使用此示例中使用的代码:Download File From A Remote URL
以下是我的修改版本:
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("2017.plist")
//let destinationFileUrl = URL(string: Bundle.main.path(forResource: String(currentYear), ofType: "plist")!)
//Create URL to the source file you want to download
let fileURL = URL(string: "https://drive.google.com/open?id=0BwHDQFwaL9DuLThNYWwtQ1VXblk")
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.removeItem(at: destinationFileUrl)
try FileManager.default.moveItem(at: tempLocalUrl, to: destinationFileUrl)
print("File was replaced")
print(NSArray(contentsOf: tempLocalUrl))
//print(tempLocalUrl)
} catch (let writeError) {
print("Error creating a file \(String(describing: destinationFileUrl)) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %@", error?.localizedDescription as Any);
}
}
task.resume()
我最初尝试覆盖与应用捆绑在一起的文件,导致错误。所以我试图将它保存在应用程序的文档文件夹中,并删除了该错误。我必须确保并删除该文件的任何先前版本,因为它在第一次运行后给我一个文件已存在错误。
虽然它表示一切正常(成功下载和替换文件的输出都会发生)当我从下载的URL打印数组内容时,它只给我nil
。
这是我第一次尝试在应用中使用任何类型的外部资源。在我总是将所有内容保持在内部之前,所以我确信有一些明显的东西是我遗失的。
更新1: 我意识到我没有用于从Google云端硬盘下载文件的正确网址。该行代码已更改为:
let fileURL = URL(string: "https://drive.google.com/uc?export=download&id=0BwHDQFwaL9DuLThNYWwtQ1VXblk")
所以现在我实际上正在下载像我原先认为的那样的plist。即使删除第一条评论中提到的删除问题,我仍然无法获取下载的文件来实际替换现有文件。
更新2: 我已将实际文件操作减少到以下内容:
do {
try FileManager.default.replaceItemAt(destinationFileUrl, withItemAt: tempLocalUrl)
print("File was replaced")
print(NSArray(contentsOf: destinationFileUrl))
} catch (let writeError) {
print("Error creating a file \(String(describing: destinationFileUrl)) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %@", error?.localizedDescription as Any);
}
执行替换后,文件的输出显示从Internet下载的正确新内容。
稍后在代码中,当我尝试访问该文件时,内容似乎再次为零。
答案 0 :(得分:1)
查看下载完成代码。你:
删除目标网址上的文件(如果有的话) 剩的)
MOVE 将临时文件移至目标网址(从
尝试从临时URL加载文件。
这张照片出了什么问题?
答案 1 :(得分:0)
您正在尝试获取已移动文件的内容。您已将文件移动到目标网址,然后尝试从临时位置获取文件的内容。
要获取文件数据,请尝试以下操作:
let fileData = try! String(contentsOf: destinationFileUrl, encoding: String.Encoding.utf8)
print(fileData)