Swift - Write Image from URL to Local File

前端 未结 6 730
一生所求
一生所求 2021-02-01 15:55

I\'ve been learning swift rather quickly, and I\'m trying to develop an OS X application that downloads images.

I\'ve been able to parse the JSON I\'m looking for into a

6条回答
  •  耶瑟儿~
    2021-02-01 16:39

    Update for swift 5

    just change filename.png to something else

    func writeImageToDocs(image:UIImage){
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    
        let destinationPath = URL(fileURLWithPath: documentsPath).appendingPathComponent("filename.png")
    
        debugPrint("destination path is",destinationPath)
    
        do {
            try image.pngData()?.write(to: destinationPath)
        } catch {
            debugPrint("writing file error", error)
        }
    }
    
    func readImageFromDocs()->UIImage?{
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    
        let filePath = URL(fileURLWithPath: documentsPath).appendingPathComponent("filename.png").path
        if FileManager.default.fileExists(atPath: filePath) {
            return UIImage(contentsOfFile: filePath)
        } else {
            return nil
        }
    }
    

提交回复
热议问题