stringByAppendingPathComponent is unavailable

IosSwiftSwift2

Ios Problem Overview


My app shares photo on Instagram, to do this it first saves it on a temporary directory:

let writePath = NSTemporaryDirectory().stringByAppendingPathComponent("instagram.igo")

It was working on Swift 1.2, but does not work on Swift 2.0.

Given error message is: >stringByAppendingPathComponent is unavailable: use URLByAppendingPathComponent on NSURL instead.

Ios Solutions


Solution 1 - Ios

It looks like the method stringByAppendingPathComponent is removed in Swift 2.0, so what the error message suggests is to use:

let writePath = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("instagram.igo")

Update:

URLByAppendingPathComponent() has been replaced by appendingPathComponent() so instead do:

let writePath = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("instagram.igo")

Solution 2 - Ios

It is working for NSString so you can use it like this:

extension String {
    func stringByAppendingPathComponent(path: String) -> String {
        let nsSt = self as NSString
        return nsSt.stringByAppendingPathComponent(path)
    }
}

Now you can use this extension which will convert your String to NSString first and then perform operation.

And your code will be:

let writePath = NSTemporaryDirectory().stringByAppendingPathComponent("instagram.igo")

Here is some another methods for use:

extension String {  

    var lastPathComponent: String {  
        return (self as NSString).lastPathComponent  
    }  
    var pathExtension: String {  
        return (self as NSString).pathExtension  
    }  
    var stringByDeletingLastPathComponent: String {  
        return (self as NSString).stringByDeletingLastPathComponent  
    }  
    var stringByDeletingPathExtension: String {  
        return (self as NSString).stringByDeletingPathExtension  
    }  
    var pathComponents: [String] {  
        return (self as NSString).pathComponents  
    }  
    func stringByAppendingPathComponent(path: String) -> String {  
        let nsSt = self as NSString  
        return nsSt.stringByAppendingPathComponent(path)  
    }  
    func stringByAppendingPathExtension(ext: String) -> String? {  
        let nsSt = self as NSString  
        return nsSt.stringByAppendingPathExtension(ext)  
    }  
}

Reference from HERE.

For swift 3.0:

extension String {
    func stringByAppendingPathComponent1(path: String) -> String {
        let nsSt = self as NSString
        return nsSt.appendingPathComponent(path)
    }
}

let writePath = NSTemporaryDirectory().stringByAppendingPathComponent(path: "instagram.igo")


extension String {
    
    var lastPathComponent: String {
        return (self as NSString).lastPathComponent
    }
    var pathExtension: String {
        return (self as NSString).pathExtension
    }
    var stringByDeletingLastPathComponent: String {
        return (self as NSString).deletingLastPathComponent
    }
    var stringByDeletingPathExtension: String {
        return (self as NSString).deletingPathExtension
    }
    var pathComponents: [String] {
        return (self as NSString).pathComponents
    }
    func stringByAppendingPathComponent(path: String) -> String {
        let nsSt = self as NSString
        return nsSt.appendingPathComponent(path)
    }
    func stringByAppendingPathExtension(ext: String) -> String? {
        let nsSt = self as NSString
        return nsSt.appendingPathExtension(ext)
    }
}

Solution 3 - Ios

Simply wrap your string as NSString.

let writePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("instagram.igo")

Solution 4 - Ios

for Swift 3:

let writePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(directoryname).path

or better create this extension:

extension String {
    func appendingPathComponent(_ string: String) -> String {
        return URL(fileURLWithPath: self).appendingPathComponent(string).path
    }
}

usage:

 let writePath = NSTemporaryDirectory().appendingPathComponent(directoryname)

Solution 5 - Ios

Swift 3 Solution:

Here is a function to get the documents directory path-

    func getDocumentsDirectory() -> URL {
         let paths = FileManager.default.urls(for: .documentDirectory, in:.userDomainMask)
         let documentsDirectory = paths[0]
         return documentsDirectory
     }

How to use:

    getDocumentsDirectory.appendingPathComponent("google.com")

Result:

    file:///var/folders/w1/3rcp2fvs1qv43hfsh5876s0h0000gn/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground-7CF9F706-509C-4D4C-997E-AB8FE9E4A6EA/Documents/google.com

Solution 6 - Ios

For swift 2.0

// Get the documents Directory
    func documentsDirectory() -> String {
        let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
        return documentsFolderPath
    }

// Get path for a file in the directory
func fileInDocumentsDirectory(filename: String) -> String {

    let writePath = (documentsDirectory() as NSString).stringByAppendingPathComponent("Mobile")
    
    if (!NSFileManager.defaultManager().fileExistsAtPath(writePath)) {
        do {
            try NSFileManager.defaultManager().createDirectoryAtPath(writePath, withIntermediateDirectories: false, attributes: nil) }
            catch let error as NSError {
                print(error.localizedDescription);
        }
    }
    return (writePath as NSString).stringByAppendingPathComponent(filename)
}

//# MARK: - Save Image in Doc dir
func saveImage (image: UIImage, path: String ) -> Bool{
    
    let pngImageData = UIImagePNGRepresentation(image)
    //        let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG
    let result = pngImageData!.writeToFile(path, atomically: true)
    
    print("\(result)")
    print("\(path)")
    
    return result
    
}

Solution 7 - Ios

You can use URLByAppendingPathComponent() instead. Please note that you should trim the path string to remove “file://“ prefix:

let uniqueFileName = NSUUID().UUIDString
let documentsDirectory = getDocumentsDirectoryURL()
	if let path = documentsDirectory?.URLByAppendingPathComponent(uniqueFileName) {
    	var pathString = path.absoluteString
        pathString = imagePathString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "file://"))
}

func getDocumentsDirectoryURL() -> NSURL? {
    let fileManager = NSFileManager()
    if let docsDirectory = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first {
    	return docsDirectory
    }
	return nil
}

Solution 8 - Ios

Do the following:

(("\(fileName)" as NSString).lastPathComponent as NSString).stringByDeletingPathExtension

Solution 9 - Ios

I tried this and it solved the problem.

before:

let localPath = documentDirectory.URLByAppendingPathComponent(imageName)

after:

let localPath = (documentDirectory as NSString).appendingPathComponent(imageName)

Solution 10 - Ios

If using NSString path methods (instead of String URL methods) is acceptable, it's much easier to extend String with a computed property or a method returning its value as NSString (instead of duplicating the desired methods in String extension):

extension String
{
    var ns: NSString { return self as NSString }
}

and then:

swiftStringPath.ns.appendingPathComponent("whateva")
swiftStringPath.ns.deletingPathExtension

Solution 11 - Ios

Swift 4

extension String {
    
    var lastPathComponent: String {
        return (self as NSString).lastPathComponent
    }
    var pathExtension: String {
        return (self as NSString).pathExtension
    }
    var stringByDeletingLastPathComponent: String {
        return (self as NSString).deletingLastPathComponent
    }
    var stringByDeletingPathExtension: String {
        return (self as NSString).deletingPathExtension
    }
    var pathComponents: [String] {
        return (self as NSString).pathComponents
    }
    func stringByAppendingPathComponent(path: String) -> String {
        let nsSt = self as NSString
        return nsSt.appendingPathComponent(path)
    }
    func stringByAppendingPathExtension(ext: String) -> String? {
        let nsSt = self as NSString
        return nsSt.appendingPathExtension(ext)
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaysamView Question on Stackoverflow
Solution 1 - IosDániel NagyView Answer on Stackoverflow
Solution 2 - IosDharmesh KheniView Answer on Stackoverflow
Solution 3 - IosJeffrey NeoView Answer on Stackoverflow
Solution 4 - IosVyacheslavView Answer on Stackoverflow
Solution 5 - IosRevanthView Answer on Stackoverflow
Solution 6 - IosMehul ChuahanView Answer on Stackoverflow
Solution 7 - IosInbal TishView Answer on Stackoverflow
Solution 8 - IosMauro DelazeriView Answer on Stackoverflow
Solution 9 - IosMiah G.View Answer on Stackoverflow
Solution 10 - IosRussianView Answer on Stackoverflow
Solution 11 - IosDuncan GroenewaldView Answer on Stackoverflow