我想在我加载的文件(.jpg)的名称中插入后缀。假设原始文件名是“AAA.jpg”并且用户指定了类似“已更改”的后缀,我想在同一文件夹中保存一个名为“AAA changed.jpg”的新文件。这是我试过的:
var noExt = chosenFiles[indexInChoseFiles].deletingPathExtension() // full_path/filename (but PercentEncoding)
let aString=noExt.absoluteString + " " + filenameSuffix + ".jpg" // insert the suffix and the extension
var bString=aString.removingPercentEncoding! // get rid of PercentEncoding
var newPath=URL(string: bString) // *** nil ***
newPath=URL(string: aString) // *** nil ***
aString和bString都没问题,但newPath在两种情况下都返回nil。
答案 0 :(得分:1)
你几乎不应该使用.absoluteString
进行操作
URL和删除百分比编码使其无效
URL字符串,以便转换回URL
失败。
以下是该问题的简化演示:
let url = URL(fileURLWithPath: "/path/to/my documents/aaa.jpg")
let path = url.absoluteString // "file:///path/to/my%20documents/aaa.jpg"
let path2 = path.removingPercentEncoding! // "file:///path/to/my documents/aaa.jpg"
let url2 = URL(string: path2) // nil
一种可能的解决方案是改为使用.path
:
let url = URL(fileURLWithPath: "/path/to/my documents/aaa.jpg")
print(url)
// "file:///path/to/my%20documents/aaa.jpg"
let path = url.deletingPathExtension().path
let newPath = path + " CHANGED" + ".jpg"
let newURL = URL(fileURLWithPath: newPath)
print(newURL)
// file:///path/to/my%20documents/aaa%20CHANGED.jpg
另一种解决方案,仅使用URL
方法:
let url = URL(fileURLWithPath: "/path/to/my documents/aaa.jpg")
print(url)
// "file:///path/to/my%20documents/aaa.jpg"
let ext = url.pathExtension // "jpg"
let basename = url.deletingPathExtension().lastPathComponent // "aaa"
let newUrl = url.deletingLastPathComponent()
.appendingPathComponent(basename + " CHANGED")
.appendingPathExtension(ext)
print(newUrl)
// "file:///path/to/my%20documents/aaa%20CHANGED.jpg"