I want to download a file and write into document directory but when I run on the simulator
, it returns error like this:
Error Domain=NSCocoaErrorDomain Code=4 "The folder “logo.jpg” doesn't exist."
I write the codes like this and what I am wrong? Thanks.
var absPath = "./image/logo.png"
var sourceUrl = "http://www.example.com/data/"
var documentUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
let strIdx = absPath.index(absPath.startIndex, offsetBy: 2)
if (absPath.hasPrefix("./"))
{
absPath = absPath.substring(from: strIdx)
}
let sourceUrl = URL(string: self.sourceUrl.appending(absPath))
let fileData = try NSData(contentsOf: sourceUrl!, options: NSData.ReadingOptions())
let destPath = documentUrl.appendingPathComponent(absPath)
do {
try fileData.write(toFile: destPath.path, options: .atomicWrite)
} catch {
print(error)
}
absPath
contains a subdirectory. If you want to save the file directly into Documents
you have to strip the image
subdirectory.
let destPath = documentUrl.appendingPathComponent(sourceUrl!.lastPathComponent)
Otherwise you have to create the image
directory in Documents
.
Note: In Swift 3 don't use NSData
and it's highly recommended to use the URL related API
do {
let fileData = try Data(contentsOf: sourceUrl!)
try fileData.write(to: sourceUrl!, options: .atomic)
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.