1.注意字符串的拼接
2.write file to url 结果 passed URL no scheme 解决方法 :
/var/containers/Bundle/Application/509FDAEA-090F-4CF0-B40F-5F3BA7586216/ZBPlayer.app/text.txt
在路径前门添加 "file://"
3. 异常捕获 do try catch
4. 在iTunes中打开documentDirectory : 在info.plist 中添加 Application supports iTunes file sharing
enum DogError :Error {
case NameInvalidError
case AgeInvalidError
case NameLengthError
}
override func viewDidLoad() {
super.viewDidLoad()
let content = "hahahaha"
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask,true)
var strPath = "/text.txt"
strPath = "file://" + documentPath[0] + strPath
let url = URL.init(string: strPath)
//异常捕获 方法一
do {
try content.write(to: url!, atomically: true, encoding: .utf8)
}
catch{
print(error)
}
//异常捕获 方法二
guard (try? content.write(to: url!, atomically: true, encoding: .utf8)) != nil
else {
return
}
}