raj kumar
raj kumar

Reputation: 69

How to set background image to the view using URL in swift

I am developing a app using swift 2.2 in my app I need to add a background image to the view which am getting from the URL I know how to add to imageview but I can't add to view.

Upvotes: -2

Views: 1889

Answers (3)

Hosny
Hosny

Reputation: 831

This work for me

 let url = NSURL(string: "https://httpbin.org/image/png")
    let data = NSData(contentsOfURL: url!)
    let image = UIImage(data: data!)
    self.view.layer.contents = image?.CGImage 

Upvotes: 0

Himanshu Moradiya
Himanshu Moradiya

Reputation: 4815

Alamofire.download("https://httpbin.org/image/png").responseData { response in
    if let data = response.result.value {
        let image = UIImage(data: data)
        self.view.backgroundColor = UIColor.init(patternImage: UIImage.init(CGImage: image.CGImage!))

    }
}

Upvotes: 1

Sivajee Battina
Sivajee Battina

Reputation: 4174

Directly you can't set image to UIView. First you need to set image to ImageView and add that ImageView as addSubView to UIView. If you want to load image asynchronously(for better performance), you can use Alamofire's code like below.

Alamofire.download("https://httpbin.org/image/png").responseData { response in
   if let data = response.result.value {
      let image = UIImage(data: data)
   }
}

Upvotes: 0

Related Questions