Swift 3 (forget about NSURL).
let fileName = "20-01-2017 22:47" let folderString = "file:///var/mobile/someLongPath"
To make a URL from a string:
let folder: URL? = Foundation.URL(string: folderString) // Optional<URL> // βΏ some : file:///var/mobile/someLongPath
If we want to add a file name. Note that appendingPathComponent () automatically adds percent encoding:
let folderWithFilename: URL? = folder?.appendingPathComponent(fileName) // Optional<URL> // βΏ some : file:///var/mobile/someLongPath/20-01-2017%2022:47
If we want to have a String, but without the root part (note that percent encoding is deleted automatically):
let folderWithFilename: String? = folderWithFilename.path
If we want to keep the root part, we do it (but remember the percentage encoding - it is not deleted):
let folderWithFilenameAbsoluteString: String? = folderWithFilenameURL.absoluteString // βΏ Optional<String> // - some : "file:///var/mobile/someLongPath/20-01-2017%2022:47"
To manually add a percent encoding for a string:
let folderWithFilenameAndEncoding: String? = folderWithFilename.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
To remove percentage encoding:
let folderWithFilenameAbsoluteStringNoEncodig: String? = folderWithFilenameAbsoluteString.removingPercentEncoding // βΏ Optional<String> // - some : "file:///var/mobile/someLongPath/20-01-2017 22:47"
Percent encoding is important because it requires URLs for network requests, and URLs in the file system do not always work - it depends on the actual method that uses them. The danger here is that they can be deleted or added automatically, so itβs better to debug these conversions.
Vitalii Jan 20 '17 at 21:40 2017-01-20 21:40
source share