简体   繁体   English

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

[英]How to convert this var string to URL in Swift

I need url filepath be a URL (NSURL in old versions of Swift).我需要 url 文件路径是一个URL (旧版本的 Swift 中的 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
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.我需要将其转换为 URL 以用于self.fileOutput.startRecording(to: <#outputFileURL: URL?#>, recordingDelegate: <#AVCaptureFileOutputRecordingDelegate?#>)方法。

I tried filePath as? URL()我试过filePath as? URL() filePath as? URL() but it isn't correct. filePath as? URL()但它不正确。

you need to do:你需要做:

let fileUrl = URL(string: filePath)

or或者

let fileUrl = URL(fileURLWithPath: filePath)

depending on your needs.取决于您的需求。 See URL docs查看URL 文档

Before Swift 3, URL was called NSURL.在 Swift 3 之前,URL 被称为 NSURL。

在 swift 3 中使用:

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

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

in swift 4 to convert to url use URL在 swift 4 中转换为 url 使用 URL

let fileUrl = URL.init(fileURLWithPath: filePath)

or或者

let fileUrl = URL(fileURLWithPath: filePath)

要将 String 中的文件路径转换为 ​​NSURL,请观察以下代码

var filePathUrl = NSURL.fileURLWithPath(path)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM