Swift - Write Image from URL to Local File

前端 未结 6 657
一生所求
一生所求 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:24

    In Swift 3:

    Write

    do {
        let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileURL = documentsURL.appendingPathComponent("\(fileName).png")
        if let pngImageData = UIImagePNGRepresentation(image) {
        try pngImageData.write(to: fileURL, options: .atomic)
        }
    } catch { }
    

    Read

    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let filePath = documentsURL.appendingPathComponent("\(fileName).png").path
    if FileManager.default.fileExists(atPath: filePath) {
        return UIImage(contentsOfFile: filePath)
    }
    

提交回复
热议问题