iosswiftsdwebimage

How do you load an external image with SDWebImage?


I'm trying to use an external image as a tab bar button. I've seen this with few apps so I thought I'd give it a go.

HackingWithWift mentioned using SDWebImage

import SDWebImage
import UIKit

class ViewController {

    let imageView = UIImageView()
    var tabBar = UITabBar()

    // viewDidLoad

    imageView.sd_setImage(with: URL(string: "https://randomuser.me/api/portraits/men/32.jpg"), placeholderImage: UIImage(named: "tablogo")) { image, error, foo, url in
        
        print(image, error, foo, url)
        
        // Assume no errors!
        
        let img = self.resizeImage(image: image!, newWidth: 25)
        
        let itemAvatar = UITabBarItem(title: "Profile", image: img, selectedImage: img)

        
        self.tabBar.frame = CGRect(x: 0, y: self.view.frame.height - 75, width: self.view.frame.width, height: 50)
        self.tabBar.items = [self.itemAvatar]
        self.view.addSubview(self.tabBar)
    }
}

Nothing happened so I thought I needed to resize the image first so I found this answer.

func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
    let scale = newWidth / image.size.width
    let newHeight = image.size.height * scale
    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
    image.draw(in: CGRectMake(0, 0, newWidth, newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
}

When the view loaded, my tab bar is shown with a square and no image.

enter image description here

How can I resolve this?


Solution

  • Try to add RenderingMode to your image

    UIImage(named: "tablogo")?.withRenderingMode(.alwaysOriginal)