- 下载数据并输出
let url = URL(string: "https://www.apple.com")!
let task = URLSession.shared.downloadTask(with: url) { localURL, urlResponse, error in
if let localURL = localURL {
if let string = try? String(contentsOf: localURL) {
print(localURL)
print(string)
}
}
}
每个应用程序都有一个沙箱存放自己的数据,沙箱中有不同的文件夹。下载后会把数据放到临时文件夹tmp中。注意这里URL的内容要是文本。
- 从临时文件夹复制到文档文件夹
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
let fileManager = FileManager.default
let newsURL = self.getDocumentsDirectory().appendingPathComponent("news.mp3")
do {
try fileManager.copyItem(at:localURL, to: newsURL)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}
- 下载文件并保存
let url = URL(string: "https://www.nhk.or.jp/r-news/ondemand/mp3/20200605170003_32512_3_1_2.mp3")!
let task = URLSession.shared.downloadTask(with: url) { localURL, urlResponse, error in
if let localURL = localURL {
print(localURL)
print(self.getDocumentsDirectory())
let fileManager = FileManager.default
// Copy 'hello.swift' to 'subfolder/hello.swift'
let newsURL = self.getDocumentsDirectory().appendingPathComponent("news.mp3")
do {
try fileManager.copyItem(at:localURL, to: newsURL)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}
}
}
task.resume()