How can I retrieve local files with NSURL?

夙愿已清 提交于 2019-11-27 17:15:29

问题


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:

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? :(


回答1:


You are trying to load a file from your file system, not from web.

For creating the NSURL you need to use fileURLWithPath: class method.

Change your method like:

Swift 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

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 URL class to construct the url instead of NSURL class. So the above code for constructing url changes to:

let url = URL(fileURLWithPath: urlpath!)



回答2:


You should use URLForResource(_:withExtension:) instead of pathForResource:

let fileUrl = Bundle.main.url(forResource: "bpreg", withExtension: "xml")



回答3:


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.



来源:https://stackoverflow.com/questions/28419188/how-can-i-retrieve-local-files-with-nsurl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!