Swift 3(忘了NSURL)。
let fileName = "20-01-2017 22:47"
let folderString = "file:///var/mobile/someLongPath"
要使用字符串制作网址:
let folder: URL? = Foundation.URL(string: folderString)
// Optional<URL>
// ▿ some : file:///var/mobile/someLongPath
如果要添加文件名。请注意,appendingPathComponent()会自动添加百分比编码:
let folderWithFilename: URL? = folder?.appendingPathComponent(fileName)
// Optional<URL>
// ▿ some : file:///var/mobile/someLongPath/20-01-2017%2022:47
当我们要使用String而不使用根部分时(请注意,百分比编码会自动删除):
let folderWithFilename: String? = folderWithFilename.path
// ▿ Optional<String>
// - some : "/var/mobile/someLongPath/20-01-2017 22:47"
如果我们想保留根部分,我们可以这样做(但要注意百分比编码-它不会被删除):
let folderWithFilenameAbsoluteString: String? = folderWithFilenameURL.absoluteString
// ▿ Optional<String>
// - some : "file:///var/mobile/someLongPath/20-01-2017%2022:47"
手动添加字符串的百分比编码:
let folderWithFilenameAndEncoding: String? = folderWithFilename.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
// ▿ Optional<String>
// - some : "/var/mobile/someLongPath/20-01-2017%2022:47"
要删除百分比编码:
let folderWithFilenameAbsoluteStringNoEncodig: String? = folderWithFilenameAbsoluteString.removingPercentEncoding
// ▿ Optional<String>
// - some : "file:///var/mobile/someLongPath/20-01-2017 22:47"
百分比编码很重要,因为网络请求的URL需要它们,而文件系统的URL并不总是有效-它取决于使用它们的实际方法。需要注意的是,它们可能会被自动删除或添加,因此最好仔细调试这些转换。