我正在尝试从远程位置下载PLIST文件,并在我正在创建的iOS应用中使用它。该文件将用于应用程序日历中的日历详细信息。目的显然是我可以更新远程文件,而不必在每次需要更改日历详细信息时将更新推向应用程序本身。
我从此示例中使用的代码开始:从远程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:我意识到我没有正确的URL可用于从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下载的正确新内容。
在我尝试访问文件时,在代码的稍后,似乎在内容中似乎是无用的。
查看您的下载完成代码。您:
-
在目标URL处删除文件(如果有一个剩余)
-
移动 temp文件到目标URL(删除从temp中删除URL)
-
尝试从温度URL加载文件。
这张照片怎么了?
您正在尝试获取移动文件的内容。您已经将文件移至目标URL,然后您正在尝试从临时位置获取文件的内容。
获取文件数据,请尝试以下内容:
let fileData = try! String(contentsOf: destinationFileUrl, encoding: String.Encoding.utf8)
print(fileData)