ch1maera
ch1maera

Reputation: 1447

Image URL to UIImage Not Working

let url = URL(string: (pinsFIREBASE[marker.snippet!]?.imageURL)!)
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
    guard let data = data, error == nil else { return }
    DispatchQueue.main.async() {
        self.postImage.image = UIImage(data: data)
    }
}

task.resume()

I have the following code that takes a url from firebase, in the form https://i.sstatic.net/6edcX.jpg, and is supposed to turn that url into a UIImage that can be placed on a view. However, while extracting the text from the firebase object works, parsing the image URL doesn't seem to be working as I get an empty view. What am I doing wrong?

Upvotes: 0

Views: 760

Answers (2)

ChokWah
ChokWah

Reputation: 105

I know why, your code works. The problem is your image link. Your imageURL's HTTP type. iOS don't like HTTP type request because it's not safe.

  • Plan A: Try a HTTPS type image link, it works.
  • Plan B: Add "App Transport Security Settings" in project info ,and set "Allow Arbitrary Loads" yes in "App Transport Security Settings" dictionary.

I suggested use Plan A, that's Apple want iOSDev to do.

Upvotes: 2

jjjjjjjj
jjjjjjjj

Reputation: 4493

You need to remove the () from after DispatchQueue.main.async(). Try this:

  let url = URL(string: (pinsFIREBASE[marker.snippet!]?.imageURL)!)
  let task = URLSession.shared.dataTask(with: url!) { data, response, error in
  guard let data = data, error == nil else { return }
  DispatchQueue.main.async {
    self.postImage.image = UIImage(data: data)
   }
 }

task.resume()

Upvotes: 0

Related Questions