113

I need url filepath be a URL (NSURL in old versions of Swift). I have this:

let paths = NSSearchPathForDirectoriesInDomains(
        .documentDirectory, .userDomainMask, true)

// NSString *documentsDirectory = [paths objectAtIndex:0];
let documentsDirectory = paths[0] as String

var filePath:String? = nil
var fileNamePostfix = 0
repeat {
    filePath =
    "\(documentsDirectory)/\(dateTimePrefix)-\(fileNamePostfix).mp4"
    fileNamePostfix += 1
} while (FileManager.default.fileExists(atPath: filePath))

I need to convert this to URL for use in self.fileOutput.startRecording(to: <#outputFileURL: URL?#>, recordingDelegate: <#AVCaptureFileOutputRecordingDelegate?#>) method.

I tried filePath as? URL() but it isn't correct.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3745888
  • 6,143
  • 15
  • 48
  • 97

5 Answers5

243

you need to do:

let fileUrl = URL(string: filePath)

or

let fileUrl = URL(fileURLWithPath: filePath)

depending on your needs. See URL docs

Before Swift 3, URL was called NSURL.

JonT
  • 55
  • 9
Jiaaro
  • 74,485
  • 42
  • 169
  • 190
17

In swift 3 use:

let url = URL(string: "Whatever url you have(eg: https://google.com)")

Sreedeepkesav M S
  • 1,165
  • 14
  • 16
  • 1
    thanks , it worked for me , earlier I was using URL.init(fileURLWithPath: <#T##String#>) which was producing wrong url. I think thats for some file path. – Rajath Kornaya Jun 05 '18 at 08:08
10

in swift 4 to convert to url use URL

let fileUrl = URL.init(fileURLWithPath: filePath)

or

let fileUrl = URL(fileURLWithPath: filePath)
Kosar
  • 170
  • 2
  • 13
9

In Swift3:
let fileUrl = Foundation.URL(string: filePath)

VivienG
  • 2,143
  • 3
  • 24
  • 43
  • 1
    This will return `nil` if the path contains strings! Use `let fileUrl = URL(fileURLWithPath: filePath)` instead. – natevw Feb 15 '18 at 21:10
  • @natev not if the fileURL string contains the scheme `"file://"` as well if it was obtained using `absoluteString` instead of the `path` property. – Leo Dabus Mar 30 '21 at 19:53
4

To Convert file path in String to NSURL, observe the following code

var filePathUrl = NSURL.fileURLWithPath(path)
itsji10dra
  • 4,603
  • 3
  • 39
  • 59