swift – 为什么我不能将字符串附加到NSURL?

swift – 为什么我不能将字符串附加到NSURL?,第1张

概述将.txt文件组件附加到URL路径不起作用: var error:NSError?let manager = NSFileManager.defaultManager()let docURL = manager.URLForDirectory(.DocumentDirectory, inDomain:.UserDomainMask, appropriateForURL:nil, create: 将.txt文件组件附加到URL路径不起作用:
var error:NSError?let manager = NSfileManager.defaultManager()let docURL = manager.URLForDirectory(.documentDirectory,inDomain:.UserDomainMask,appropriateForURL:nil,create:true,error:&error)docURL.URLByAppendingPathComponent("/Ricfile.txt") <-- doesn't work

通过调试器:

file:///Users/Ric/library/Developer/CoreSimulator/Devices/<device ID>/data/Containers/Data/Application/<app ID>/documents/

使用docURL将字符串写入文件不起作用,因为缺少文件名.

原因(通过错误):

“The operation Couldn’t be completed. Is a directory”

所以问题:为什么以下不起作用?

docURL.URLByAppendingPathComponent("/Ricfile.txt")
URLByAppendingPathComponent:不会改变现有的NSURL,它会创建一个新的NSURL.从 documentation:

URLByAppendingPathComponent: Returns a new URL made by appending a
path component to the original URL.

您需要将方法的返回值赋给某些东西.例如:

let directoryURL = manager.URLForDirectory(.documentDirectory,error:&error)let docURL = directoryURL.URLByAppendingPathComponent("/Ricfile.txt")

更好的方法是使用NSURL(string:String,relativeTo:NSURL):

let docURL = NSURL(string:"Ricfile.txt",relativeTo:directoryURL)
总结

以上是内存溢出为你收集整理的swift – 为什么我不能将字符串附加到NSURL?全部内容,希望文章能够帮你解决swift – 为什么我不能将字符串附加到NSURL?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1029735.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存