chickenpup
chickenpup

Reputation: 11

Swift 5 UIButton with image causing my apps freezing after open url

I have an application that needs to open third-party apps (i.e Whatsapp), it runs smoothly when I build this app using Xcode 10, but in Xcode 12, it's causing the freeze. Does anyone have to face this problem before?

My code was like this

  1. declaring button
let buttonWA: UIButton = {
        let v = UIButton()
        v.imageView?.contentMode = .scaleAspectFit
        v.setImage(UIImage(named: "ic_whatsapp"), for: .normal)
        return v
    }()
    
    let buttonEmail: UIButton = {
        let v = UIButton()
        v.imageView?.contentMode = .scaleAspectFit
        v.setImage(UIImage(named: "ic_email"), for: .normal)
        return v
    }()

Then I add some functions to be called each button

@objc func WaPressed() {
        let no = "*************".urlwithPercentEscapes()
        let urlWhatsApp = "whatsapp://send?phone=\(no)"
        self.openUrl(urlString: urlWhatsApp)
    }
    
    
    @objc func EmailPressed() {
        self.openUrl(urlString: "mailto:[email protected]")
    }

func openUrl(urlString: String) {
        guard let url = URL(string: urlString) else {
            return
        }
        
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(url)
        }
    }

Everything running smoothly, and open third apps very well, but when I returning back to my apps, it goes freeze without telling me anything

I've tried change ".normal" options to other options like ".application" etc in the line

        v.setImage(UIImage(named: "ic_whatsapp"), for: .normal)

and it makes my apps running well again, but I need this "for: .normal" state so bad.

Then I've tried to change

        v.setImage(UIImage(named: "ic_whatsapp"), for: .normal)

to

v.setBackgroundImage(UIImage(named: "ic_whatsapp"), for: .normal)

and it works, but then the image scale is messy.

Could anybody help me to solve this?

Upvotes: 0

Views: 173

Answers (1)

chickenpup
chickenpup

Reputation: 11

After trying other options, I figure it out with add RenderingMode when I set Image in my button, the code looks like this:

For whatsapp button

v.setImage(UIImage(named: "ic_whatsapp").withRenderingMode(.alwaysOriginal), for: .normal)

For email button

v.setImage(UIImage(named: "ic_email").withRenderingMode(.automatic), for: .normal)

I don't understand why I can't set "automatic / alwaysOriginal" both. But this way works for me.

Thankyou

Upvotes: 1

Related Questions