Loading/Downloading image from URL on Swift

前端 未结 30 3220
感动是毒
感动是毒 2020-11-21 05:39

I\'d like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I\'ve a compilation error:

30条回答
  •  深忆病人
    2020-11-21 06:12

    Xcode 8Swift 3

    Leo Dabus's answer is awesome! I just wanted to provide an all-in-one function solution:

    let url = URL(string: 
        "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png")
    
    let task = URLSession.shared.dataTask(with: url!) { data, response, error in
        guard let data = data, error == nil else { return }
    
        DispatchQueue.main.async() {    // execute on main thread
            self.imageView.image = UIImage(data: data)
        }
    }
    
    task.resume()
    

提交回复
热议问题