ios 如何使用 NSURL 检索本地文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28419188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I retrieve local files with NSURL?
提问by Philip Ulrich
I'm here with a question that probably has a really simple answer that I am overlooking... how can I retrieve local files with NSURL? I have this here:
我在这里提出了一个问题,该问题可能有一个非常简单的答案,但我忽略了……如何使用 NSURL 检索本地文件?我这里有这个:
override func viewDidLoad() {
super.viewDidLoad()
var urlpath = NSBundle.mainBundle().pathForResource("bpreg", ofType: "xml")
let url:NSURL = NSURL(string: urlpath!)!
parser = NSXMLParser(contentsOfURL: url)!
parser.delegate = self
parser.parse()
}
But after it successfully builds it hangs on var urlpath. I've searched around and tried a few suggestions here and other places to no avail. Please help? :(
但是在它成功构建后,它挂在 var urlpath 上。我四处搜索并在这里和其他地方尝试了一些建议,但无济于事。请帮忙?:(
回答by Midhun MP
You are trying to load a file from your file system, not from web.
您正在尝试从您的文件系统加载文件,而不是从 Web 加载。
For creating the NSURL
you need to use fileURLWithPath:class method.
要创建NSURL
您需要使用fileURLWithPath:类方法。
Change your method like:
改变你的方法,如:
Swift 2
斯威夫特 2
override func viewDidLoad()
{
super.viewDidLoad()
var urlpath = NSBundle.mainBundle().pathForResource("bpreg", ofType: "xml")
let url:NSURL = NSURL.fileURLWithPath(urlpath!)!
parser = NSXMLParser(contentsOfURL: url)!
parser.delegate = self
parser.parse()
}
Swift 3
斯威夫特 3
override func viewDidLoad()
{
super.viewDidLoad()
let urlpath = Bundle.main.path(forResource: "bpreg", ofType: "xml")
let url = NSURL.fileURL(withPath: urlpath!)
parser = XMLParser(contentsOf: url)!
parser.delegate = self
parser.parse()
}
Note:In Swift 3 you can also use the URLclass to construct the url instead of NSURL
class. So the above code for constructing url changes to:
注意:在 Swift 3 中,您还可以使用URL类来构造 url 而不是NSURL
类。所以上面构造url的代码改为:
let url = URL(fileURLWithPath: urlpath!)
回答by Leo Dabus
You should use URLForResource(_:withExtension:) instead of pathForResource:
您应该使用 URLForResource(_:withExtension:) 而不是 pathForResource:
let fileUrl = Bundle.main.url(forResource: "bpreg", withExtension: "xml")
回答by Christian
Your file doesn't exist in your main-bundle yet.
您的主包中尚不存在您的文件。
You have to add the file your are using to your Bundle Resource.
您必须将您正在使用的文件添加到您的捆绑资源中。
So to add it. Go to App Target -> Build Phases
and check the Bundle Resource
and add it by drag n' drop.
所以要添加它。转到App Target -> Build Phases
并检查Bundle Resource
并通过拖放添加它。