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? :(
They are identical in usage, Apple has chosen to drop the NeXTSTEP prefix in support of using foundation with Swift on multiple platforms like iOS, Android, and Linux. from Apple: "The Swift overlay to the Foundation framework provides the URL structure, which bridges to the NSURL class.
An NSURL object is composed of two parts—a potentially nil base URL and a string that is resolved relative to the base URL. An NSURL object is considered absolute if its string part is fully resolved without a base; all other URLs are considered relative.
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:
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() }
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With