user8889350
user8889350

Reputation: 117

Insert a character in the filename

I want to insert a suffix in the name of a file (.jpg) I loaded. Say the original filename is "AAA.jpg" and the user specified a suffix like "changed", I want to save in the same folder a new file named "AAA changed.jpg". Here is what I tried:

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 and bString are OK, but newPath returns nil in both cases.

Upvotes: 1

Views: 46

Answers (1)

Martin R
Martin R

Reputation: 539685

You almost never should use .absoluteString for the manipulation of URLs, and removing the percent encoding makes it an invalid URL string, so that the conversion back to URL fails.

Here is a simplified demonstration of the problem:

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

One possible solution is to use .path instead:

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

Another solution, using only URL methods:

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"

Upvotes: 1

Related Questions