0

I create a left nav bar button but I don't know how to store image from url into the button image. Below is my nav bar left button code

     navigationItem.leftBarButtonItem = UIBarButtonItem(image: <#T##UIImage?#>, style: .plain, target: self, action: #selector(handleButtonPressed))

Should I create an UIimage variable and then use it for image param? Any suggestions? Thanks!

KevinVuD
  • 581
  • 2
  • 5
  • 25
  • 1
    First you have to figure out how to download images https://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift – Lukas Würzburger Mar 19 '18 at 18:47

2 Answers2

0

You need to download the image first. So for the download time you either setup a placeholder image or don't show it at all. But this code should help you.

fund viewDidLoad() {
    super.viewDidLoad()
    let placeholderImage = UIImage(named: "placeholder")
    updateLeftNavigationItem(with: placeholderImage)
    loadNavigationBarImage(from: URL(string: "<your url>")!)
}

func updateLeftNavigationItem(with image: UIImage?) {
    navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(handleButtonPressed))
}

func loadNavigationBarImage(from url: URL) {
    getDataFromUrl(url: url) { data, response, error in
        guard let data = data, error == nil else { return }
        DispatchQueue.main.async() { [weak self] in
            let image = UIImage(data: data)
            self?.updateLeftNavigationItem(with: image)
        }
    }
}

func getDataFromUrl(url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
    URLSession.shared.dataTask(with: url) { data, response, error in
        completion(data, response, error)
    }.resume()
}

For the initial state

Lukas Würzburger
  • 6,543
  • 7
  • 41
  • 75
0

You can set the image from url to the bar button like this: First convert url into data and then convert into UIImage and then use it

let url = URL(string:"http://www.apple.com/euro/ios/ios8/a/generic/images/og.png")

if let data = try? Data(contentsOf: url!)
{
  let Serverimage: UIImage = UIImage(data: data)
  let barButton = UIBarButtonItem(image: Serverimage, landscapeImagePhone: nil, style: .Done, target: self, action: #selector(handleButtonPressed))
  self.navigationItem.leftBarButtonItem = barButton

}

All the best. Hope this will help you.

Harish Singh
  • 765
  • 1
  • 12
  • 23