Search code examples
iosswift3nsstringnsurl

Change URL last component name and add extension to the renamed one


I have the following URL

file:///Users/ivancantarino/Library/Developer/CoreSimulator/Devices/CCE2FCA5-05F0-4BB7-9A25-CBC168398A62/data/Containers/Data/Application/E48179F9-84FB-4CB3-B993-1E33FCFB5083/Library/Caches/CloudKit/34af81edf8344be1cf473ef394e06ccc8e1bc8cf/Assets/AE86E028-E4E0-45D5-B5FE-BAE975D07F2A.0166f7df06d2562d8d53e70a3779a46de3769584c3

I'm trying to rename the last part component of this url, but still having a url not only the filename.

I've managed to access the last part with the following code:

func extractAndBreakFilenameInComponents(fileURL: NSURL) {  
    let fileURLParts = fileURL.path!.components(separatedBy: "/")
    let fileName = fileURLParts.last
    print("filename:", fileName)
    // prints: AE86E028-E4E0-45D5-B5FE-BAE975D07F2A.0166f7df06d2562d8d53e70a3779a46de3769584c3
}

I want to change the fileName to something like myFile.pdf but keeping the URL

It is a simple URL rename, not creating a new one, just changing the existing one

What's the best approach on this?

Thank you


Solution

  • You can also do with this way

    var url = URL.init(string: "http://www.example.com/test123")
    
    url?.deleteLastPathComponent()
    url?.appendPathComponent("file.pdf")
    
    
    print(url)
    

    Output :http://www.example.com/file.pdf

    Hope it helps to you

    EDIT

    You need to rename file use following code

    1) Create Copy and update last component

    var urlNew = URL.init(string: "http://www.example.com/test123")
    
    urlNew?.deleteLastPathComponent()
    urlNew?.appendPathComponent("file.pdf")
    
    
    
                  do {
                        try FileManager.default.moveItem(atPath: oldURL!, toPath: urlNew)
                    } catch {
    
                    }