Thursday, May 12, 2016

Saving Files on iOS Device

It is possible to save files directly to your iOS device. Here is an example of a class that saves images as PNG to the Document Directory.
class ImageData {
    
    func saveImageAsPng(image: UIImage) -> String {
        let newImageName = "image\(NSUUID().UUIDString).png"
        let fullPath = getFullPath(newImageName)
        let imageData = UIImagePNGRepresentation(image)
        imageData?.writeToFile(fullPath, atomically: true)
        return newImageName
    }
    
    func getImage(imageName: String) -> UIImage? {
        let fullPath = getFullPath(imageName)
        return UIImage(named: fullPath)
    }
    
    func clearImagesFolder() {
        let fileManager = NSFileManager.defaultManager()
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, 
            .UserDomainMask, true)[0]
        
        do {
            try fileManager.removeItemAtPath(path)
        } catch {
            print("Could not clear image folder: \(error)")
        }
    }
    
    func getFullPath(imageName: String) -> String {
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
        return "\(path)\(imageName)"
    }
}

(Swift 2.2)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...