Swift3.0 文件写入时 no scheme

在使用Swift进行文件读取时系统输出错误Error Domain=NSCocoaErrorDomain Code=518

CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme. Error Domain=NSCocoaErrorDomain Code=518 “The file couldn’t be saved because the specified URL type isn’t supported.”

原因

查看相关源文件
Data
url必须是一个本地位置,所以需要使用本地文件传输协议File Protocol

解决

  • let url = URL(string: "file://\(fileURLpath)")
  • let url = URL.init(fileURLWithPath: str)

其他

1
2
3
open func write(to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws

open func write(toFile path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws

demo with dotrycatch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let homePath = NSHomeDirectory()
// let basePath = "file://".appending(homePath).appending("/")
let basePath = "file://" + homePath + "/"
// string
let string = "hello word"
// let stringPath = basePath.appending("string.txt")
let stringPath = basePath + "string.txt"

let stringUrl = URL(string: stringPath)

do {
try string.write(to: stringUrl!, atomically: true, encoding: .utf8)

} catch {
print(error)
}

参考链接