Swift 3:无法将文件写入文档目录

时间:2017-09-11 04:27:27

标签: ios swift3

我想下载一个文件并写入文档目录但是当我在simulator上运行时,它会返回如下错误:

  

错误Domain = NSCocoaErrorDomain Code = 4“文件夹”logo.jpg“不存在。”

我写这样的代码,我错了什么?感谢。

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)
}

1 个答案:

答案 0 :(得分:0)

absPath包含一个子目录。如果要将文件直接保存到Documents,则必须删除image子目录。

let destPath = documentUrl.appendingPathComponent(sourceUrl!.lastPathComponent)

否则,您必须在image中创建Documents目录。

注意:在Swift 3中,请勿使用NSData,强烈建议您使用与网址相关的API

do {
    let fileData = try Data(contentsOf: sourceUrl!)  
    try fileData.write(to: sourceUrl!, options: .atomic)
...