Loading/Downloading image from URL on Swift

前端 未结 30 2517
感动是毒
感动是毒 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 05:56

    Swift 2.0 :

    1)

    if let url = NSURL(string: "http://etc...") {
        if let data = NSData(contentsOfURL: url) {
            imageURL.image = UIImage(data: data)
        }        
    }
    

    OR

    imageURL.image =
        NSURL(string: "http:// image name...")
        .flatMap { NSData(contentsOfURL: $0) }
        .flatMap { UIImage(data: $0) }
    

    2) Add this method to VC or Extension.

    func load_image(urlString:String)
    {   let imgURL: NSURL = NSURL(string: urlString)!
        let request: NSURLRequest = NSURLRequest(URL: imgURL)
    
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse?, data: NSData?, error: NSError?) in
    
            if error == nil {
                self.image_element.image = UIImage(data: data)
            }
        }
    }
    

    Usage :

    self.load_image(" url strig here")
    

提交回复
热议问题