如何在swift中将此var字符串转换为NSURL

use*_*888 67 nsurl ios swift

我需要url filepath是一个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))
Run Code Online (Sandbox Code Playgroud)

我需要将它转换为NSURL以便在self.fileOutput.startRecordingToOutputFileURL(<#outputFileURL:NSURL?#>,recordingDelegate:<#AVCaptureFileOutputRecordingDelegate?#>)方法中使用.

我试过self.fileOutput.startRecording(to: <#outputFileURL: URL?#>, recordingDelegate: <#AVCaptureFileOutputRecordingDelegate?#>)但不正确

谢谢!

Jia*_*aro 142

你需要做的:

let fileUrl = URL(string: filePath)
Run Code Online (Sandbox Code Playgroud)

要么

let fileUrl = URL(fileURLWithPath: filePath)
Run Code Online (Sandbox Code Playgroud)

根据您的需要.请参阅NSURL文档


Sre*_*M S 14

在swift 3中使用:

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


Viv*_*enG 9

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


Kos*_*sar 5

在swift 4中转换为url使用URL

let fileUrl = URL.init(fileURLWithPath: filePath)
Run Code Online (Sandbox Code Playgroud)

要么

let fileUrl = URL(fileURLWithPath: filePath)
Run Code Online (Sandbox Code Playgroud)