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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:05:44  来源:igfitidea点击:

How to convert this var string to URL in Swift

iosswiftnsurl

提问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

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。

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