ios 如何在 Swift 中将此 var 字符串转换为 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24410473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert this var string to URL in Swift
提问by user3745888
I need url filepath be a URL(NSURL in old versions of Swift). I have this:
我需要 url 文件路径是一个URL(旧版本的 Swift 中的 NSURL)。我有这个:
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()
but it isn't correct.
我试过了,filePath as? URL()
但它不正确。
回答by Jiaaro
回答by Sreedeepkesav M S
In swift 3 use:
在 swift 3 中使用:
let url = URL(string: "Whatever url you have(eg: https://google.com)")
let url = URL(string: "Whatever url you have(eg: https://google.com)")
回答by VivienG
In Swift3:let fileUrl = Foundation.URL(string: filePath)
在 Swift3 中:let fileUrl = Foundation.URL(string: filePath)
回答by Kosar
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)
回答by user2342053
To Convert file path in String to NSURL, observe the following code
要将 String 中的文件路径转换为 NSURL,请观察以下代码
var filePathUrl = NSURL.fileURLWithPath(path)