Search code examples
swiftfilesystems

How to append a string to a URL in Swift?


Given a name of a file like this:

let fileName = "example.jpg"

I am grabbing the URL of this directory using a helper function, which returns the URL to me:

let imagesURL = getURL()

How can I append the string fileName to the imagesURL such that it returns something like this:

/path/to/images/dir/example.jpg

How do I get it in both String and URL format?


Solution

  • This gives you a new URL with the fileName appended:

    let appended = imagesURL.appendingPathComponent(fileName)
    

    And this converts it back to a string:

    let strVersion = appended.absoluteString //full URL
    let strVersion2 = appended.path //path only