How to convert this var string to URL in Swift

IosSwiftNsurl

Ios Problem Overview


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.

Ios Solutions


Solution 1 - Ios

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.

Solution 2 - Ios

In swift 3 use:

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

Solution 3 - Ios

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

Solution 4 - Ios

in swift 4 to convert to url use URL

let fileUrl = URL.init(fileURLWithPath: filePath)

or

let fileUrl = URL(fileURLWithPath: filePath)

Solution 5 - Ios

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

var filePathUrl = NSURL.fileURLWithPath(path)
       

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3745888View Question on Stackoverflow
Solution 1 - IosJiaaroView Answer on Stackoverflow
Solution 2 - IosSreedeepkesav M SView Answer on Stackoverflow
Solution 3 - IosVivienGView Answer on Stackoverflow
Solution 4 - IosKosarView Answer on Stackoverflow
Solution 5 - Iosuser2342053View Answer on Stackoverflow