Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert this var string to URL in Swift

Tags:

ios

swift

nsurl

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.

like image 754
user3745888 Avatar asked Jun 25 '14 13:06

user3745888


People also ask

How do I create a URL in Swift?

Basic URL Operations It all starts with basic operations to create and work with links. For example, you can convert a String value into a URL as follows: let url = URL(string: "https://www.avanderlee.com")! That looks a lot more swiftly and allows us to keep our implementation code clean from unwraps!


2 Answers

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.

like image 197
Jiaaro Avatar answered Oct 15 '22 00:10

Jiaaro


In swift 3 use:

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

like image 17
Sreedeepkesav M S Avatar answered Oct 15 '22 01:10

Sreedeepkesav M S