Untitled

 avatar
unknown
swift
a month ago
1.8 kB
2
Indexable
func createLocalDirectory() -> URL{
    let DocumentDirectory = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
    let appPath = DocumentDirectory.appendingPathComponent(“AppFolder")
    let databasePath = appPath?.appendingPathComponent("Images")
    do
    {
        try FileManager.default.createDirectory(atPath: databasePath!.path, withIntermediateDirectories: true, attributes: nil)
        print("Local Directory: ",databasePath as Any)
        return databasePath ?? URL(fileURLWithPath: "")
    }
    catch let error as NSError
    {
        print("Unable to create directory \(error.debugDescription)")
    }
    
    return URL(fileURLWithPath: "")
}


func saveImgToLocal(imageName: String, image: UIImage) -> String{
    if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
        
        // Create a unique file name for the image (you can use your own naming convention)
        let uniqueFilename = imageName
        
        // Append the file name to the document directory URL to get the complete file URL
        
        let imagePath = createLocalDirectory()
        
        let fileURL = imagePath.appendingPathComponent(uniqueFilename)
        
        // Convert the image to Data
        if let imageData = image.pngData() {
            
            // Write the image data to the file URL
            do {
                try imageData.write(to: fileURL)
                
                // Image has been successfully saved
                print("Image saved to: \(fileURL.path)")
                return fileURL.path
            } catch {
                print("Error saving image: \(error)")
            }
        }
    }
    return ""
}
Editor is loading...
Leave a Comment