How to save a remote image with Swift?

前端 未结 2 2014
自闭症患者
自闭症患者 2021-01-31 20:52

I\'m trying to display and save images with Swift. On first hit, it shows the remote image on imageview, on second hit it shows blank imageview instead of it should be local ima

2条回答
  •  滥情空心
    2021-01-31 21:33

    To answer your main question, you're calling the wrong UIImage initializer. You should be calling UIImage(contentsOfFile: imagePath) in swift 2 and UIImage(contentsOf: imagePath) in swift 3.

    Additionally, it looks like you're trying to do your remote fetch in the background with dispatch_async (or DispatchQueue in swift 3), but you're passing it the main queue, so you're actually blocking the main/UI thread with that. You should dispatch it to one of the background queues instead and then dispatch back to the main queue when you actually set the image in your UI:

    Swift 3 :

    DispatchQueue.global(qos: DispatchQoS.background.qosClass).async {
        do {
            let data = try Data(contentsOf: URL(string: self.remoteImage)!)
            let getImage = UIImage(data: data)
            try UIImageJPEGRepresentation(getImage!, 100)?.write(to: imagePath)
            DispatchQueue.main.async {
                self.image?.image = getImage
                return
            }
        }
        catch {
                return
        }
    }
    

    Swift 2 :

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
        let getImage =  UIImage(data: NSData(contentsOfURL: NSURL(string: self.remoteImage)))
        UIImageJPEGRepresentation(getImage, 100).writeToFile(imagePath, atomically: true)
    
        dispatch_async(dispatch_get_main_queue()) {
            self.image?.image = getImage
            return
        }
    }
    

    @Rob's answer re: fetching your remote image and saving it is really the best way to do this.

提交回复
热议问题