如何在 Swift 中将这个 var 字符串转换为 URL

我需要一个网址文件路径是 网址(NSURL 在旧版本的 Swift)。我有这样:

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))

我需要将其转换为在 self.fileOutput.startRecording(to: <#outputFileURL: URL?#>, recordingDelegate: <#AVCaptureFileOutputRecordingDelegate?#>)方法中使用的 URL。

我试了 filePath as? URL(),但它不正确。

159337 次浏览

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.

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

var filePathUrl = NSURL.fileURLWithPath(path)

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

In swift 3 use:

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

in swift 4 to convert to url use URL

let fileUrl = URL.init(fileURLWithPath: filePath)

or

let fileUrl = URL(fileURLWithPath: filePath)