How to convert this var string to NSURL in swift

2019-03-08 17:54发布

问题:

I need url filepath be a NSURL. 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
        do {
            filePath =
            "\(documentsDirectory)/\(dateTimePrefix)-\(fileNamePostfix++).mp4"
        } while (NSFileManager.defaultManager().fileExistsAtPath(filePath))

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

I tried filePath as? NSURL() but isn't correct

Thanks!

回答1:

you need to do:

let fileUrl = NSURL(string: filePath)

or

let fileUrl = NSURL(fileURLWithPath: filePath)

depending on your needs. See NSURL docs



回答2:

In swift 3 use:

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



回答3:

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



回答4:

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

var filePathUrl = NSURL.fileURLWithPath(path)


回答5:

in swift 4 to convert to url use URL

let fileUrl = URL.init(fileURLWithPath: filePath)

or

let fileUrl = URL(fileURLWithPath: filePath)


标签: swift nsurl ios8