[swift] Save image into Library folder on device

How to Save image into Library folder on device, is below code

when save data by pngImageData.write, if no [file://] on URL, Error will be happened

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

     // get selected cell information
     let cell = self.tableView.cellForRow(at: indexPath)
     let imageView = cell?.contentView.viewWithTag(1) as! UIImageView

     let fileURL = URL(string: "https://xxxxxxx/yyy.gif")

     //delete extension by deletingPathExtension, get filename by lastPathComponent
     let fileName:String = (fileURL?.deletingPathExtension().lastPathComponent)!
     saveImage(image: image, filename: fileName){(path: String) in
        //write code after complete to save file.


//Function for saving
func saveImage(image: UIImage, filename : String ,completion: (_ path: String) -> Void) {
    //Create the document folder path
    let path = "file://"+fileInLibraryDirectory(filename: filename)+".png"
    let url:URL = NSURL(string: path)! as URL
    //for png
    let pngImageData = UIImagePNGRepresentation(image)
    //for jpeg
    //let jpgImageData = UIImageJPEGRepresentation(image, 1.0)
    //let result = pngImageData!.writeToFile(path, atomically: true)
    do {
        try pngImageData?.write(to: url, options: .atomic)
        completion(path) //return path.
    } catch {
        print("saveImage error is \(error)")

//MARK: in the case of save on Documents folder
func getDocumentsURL() -> NSURL {
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    return documentsURL as NSURL

func fileInDocumentsDirectory(filename: String) -> String {
    let fileURL = getDocumentsURL().appendingPathComponent(filename)
    return fileURL!.path

//MARK: in the case of save on Library folder
func getLibraryURL() -> NSURL {
    let libraryURL = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0]
    return libraryURL as NSURL

func fileInLibraryDirectory(filename: String) -> String {
    let folderName = "media"
    createDirectory(foldername: folderName)
    let fileURL = getLibraryURL().appendingPathComponent("\(folderName)/\(filename)")
    return fileURL!.path

//MARK:Create Directory
func createDirectory(foldername : String){
    let fileManager = FileManager.default

    //for creating folder on Document folder
    //let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(foldername)

    //for creating folder on Library folder
    let paths = (NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(foldername)
    if !fileManager.fileExists(atPath: paths){
        try! fileManager.createDirectory(atPath: paths, withIntermediateDirectories: true, attributes: nil)
        print("Already dictionary created.")

For read image file saved, Refer below code

        let fileManager = FileManager.default
        let imagePath = fileInLibraryDirectory(filename: person.value(forKeyPath: "filename") as! String)
        if fileManager.fileExists(atPath: imagePath){
            cell.imageView?.image = UIImage(contentsOfFile: imagePath)
            print("No Image")


メールアドレスが公開されることはありません。 が付いている欄は必須項目です