How to convert code objective c to Swift to save image?

user3745888 picture user3745888 · Jun 19, 2014 · Viewed 9.2k times · Source

I have seen this code in other post, for save pictures:

  // Create path.
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,      NSUserDomainMask, YES);
 NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];

// Save image.
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];

An d I'm trying convert to swift for save a picture take with avfoundatioin but I dont know type NSDocumentDirectory and NSUserDomainMask here How can convert this??

Thanks!!

Answer

Grimxn picture Grimxn · Jun 19, 2014

As follows:

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
    if paths.count > 0 {
        if let dirPath = paths[0] as? String {
            let readPath = dirPath.stringByAppendingPathComponent("Image.png")
            let image = UIImage(named: readPath)
            let writePath = dirPath.stringByAppendingPathComponent("Image2.png") 
            UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true)
        }
    }
}

"paths" is an AnyObject[], so you have to check that its elements can be converted to String.

Naturally, you wouldn't actually use "NSDocumentDirectory" as the name, I just did it for clarity.

Update for Xcode 7.2

NSSearchPathForDirectoriesInDomains now returns [String] rather than [AnyObject]? so use

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first {
    // ...
}

The fact that .stringByAppendingPathComponent is also deprecated is dealt with in this answer...