How to convert this var string to URL in Swift

a 夏天 提交于 2019-12-03 02:54:25

问题


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.


回答1:


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.




回答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:


in swift 4 to convert to url use URL

let fileUrl = URL.init(fileURLWithPath: filePath)

or

let fileUrl = URL(fileURLWithPath: filePath)



回答5:


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

var filePathUrl = NSURL.fileURLWithPath(path)


来源:https://stackoverflow.com/questions/24410473/how-to-convert-this-var-string-to-url-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!