Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

ios - How can I retrieve local files with NSURL?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...