14

In Swift 2, I had used the following code:

let path = NSBundle.mainBundle().pathForResource("Document", ofType: "pdf")!
let url = NSURL.fileURLWithPath(path)
webView.loadRequest(NSURLRequest(URL: url))

Now, using Xcode 8 and Swift 3, Xcode automatically translated it to:

let path = Bundle.main.pathForResource("Translation", ofType: "pdf")!
let url = URL.fileURL(withPath: path)
webView.loadRequest(URLRequest(url: url))

On the second line, with the declaration of url, Xcode gives me the following error:

Type 'URL' has no member 'fileURL'

How can I fix this error? Thanks!

1
  • 1
    Actually the proper syntax for line two in Swift 2 is let url = NSURL(fileURLWithPath:path) (although the class method seems to work), that's why the translation failed.
    – vadian
    Commented Jul 17, 2016 at 15:26

2 Answers 2

23

The URL struct in Swift 3 has an initializer for that

let url = URL(fileURLWithPath: path)
4

If you do not use path later, you can write something like this:

let url = Bundle.main.urlForResource("Translation", withExtension: "pdf")
1
  • path property will always be available to your url if url.isFileURL is true, just check it to know if url.path is suitable for input into FileManager.
    – Leo Dabus
    Commented Jul 18, 2016 at 3:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.