-1

I am trying to parse a image from a url the url is https://a.ppy.sh/9795284

it doesn't have a specific image extension as far as i can tell, it's just a link my current code (which works for getting the username and when I print the user_id i do get 9795284 so I know the code works (I also already get other information I wanted to get since as the username however I can not for the life of me get the users image to show here is my code for dealing with parsing

    fetchCoursesJSON { (res) in
        switch res {
        case .success(let playerinfo):
            playerinfo.forEach({ (player) in
                print(player.username)
                DispatchQueue.main.async {
                    self.myLabel.text = player.username
                    self.avatar.image = UIImage(named: "https://a.ppy.sh/\(player.user_id)")
                }

            })
        case .failure(let err):
            print("Failed to fetch courses:", err)
        }
    }

I expected the output to show the users profile pick in the avatar image but it does not it's just blank.

  • `UIImage(named:)` is for loading images that you ship with your app, it won't load an image from a url. See: https://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift – dan May 03 '19 at 21:46

2 Answers2

0

You need to download the image first, you can do this by using a lib like SDWebImage, AlamofireImage, Kingfisher or using the native URLSession

The UIImage(named:) is used when the resource is in your assets.

Leandro P
  • 213
  • 4
  • 12
0

The UIImage(named:) will attempt to retrieve the image from your app.. not from the internet. Here is some code that will help you retrieve the image from your url:

guard let url = URL(string: yourUrlString ?? "") else { return }
            URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) -> Void in
                guard let data = data, error == nil else { return }
                let image = UIImage(data: data)
                DispatchQueue.main.async {
                    self.avatar.image = image
                }
            }).resume()