背景
電商項(xiàng)目總喜歡在特定節(jié)日展示不同的icon圖標(biāo)出嘹,但是為了修改圖標(biāo)而更新版本的話席楚,沒(méi)那個(gè)必要。
這里介紹一種不需要通過(guò)更新版本就可以動(dòng)態(tài)修改APP圖標(biāo)的方法税稼。
??注意:該方法在iOS10.3及以上有效
實(shí)現(xiàn)
- 1 導(dǎo)入待替換的新圖片烦秩,放到項(xiàng)目工程新文件夾中;
- 2 配置 Info.plist 文件:
<key>CFBundleIcons</key>
<dict>
<key>CFBundleAlternateIcons</key>
<dict>
<key>icon1</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>icon1</string>
</array>
<key>UIPrerenderedIcon</key>
<false/>
</dict>
<key>icon2</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>icon2</string>
</array>
<key>UIPrerenderedIcon</key>
<false/>
</dict>
</dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon60x60</string>
</array>
</dict>
</dict>
- 3 通過(guò)代碼替換
if #available(iOS 10.3, *) {
if UIApplication.shared.supportsAlternateIcons {
print("you can change this app's icon")
}else {
print("you cannot change this app's icon")
return
}
if let name = UIApplication.shared.alternateIconName {
// CHANGE TO PRIMARY ICON 恢復(fù)默認(rèn) icon
UIApplication.shared.setAlternateIconName(nil) { (err:Error?) in
print("set icon error:\(String(describing: err))")
}
print("the alternate icon's name is \(name)")
}else {
// CHANGE TO ALTERNATE ICON 指定icon圖標(biāo)
UIApplication.shared.setAlternateIconName("icon1") { (err:Error?) in
print("set icon error:\(String(describing: err))")
}
}
}
- 4 去掉更換圖標(biāo)時(shí)的彈框
更換圖標(biāo)時(shí)會(huì)出現(xiàn)系統(tǒng)彈框郎仆,可以使用Runtime來(lái)隱藏彈框只祠,這樣方便在節(jié)日時(shí)候程序自動(dòng) 無(wú)感 更改APP 的icon
具體代碼如下:
extension UIViewController {
//通過(guò)運(yùn)行時(shí)替換系統(tǒng)的present方法
public class func nkReplaceSystemPresent(){
let systemSelector = #selector(UIViewController.present(_:animated:completion:))
let nkSelector = #selector(UIViewController.newPesent(_:animated:completion:))
let systemMethod = class_getInstanceMethod(self, systemSelector)
let nkNewMethod = class_getInstanceMethod(self, nkSelector)
method_exchangeImplementations(systemMethod!, nkNewMethod!)
}
@objc public func newPesent(_ vcToPresent:UIViewController, animated flag:Bool, completion: (() ->Void)? = nil) {
if vcToPresent.isKind(of:UIAlertController.self) {
let alertController = vcToPresent as? UIAlertController
if alertController?.title==nil && alertController?.message==nil {
return
}
}
self.newPesent(vcToPresent, animated: flag)
}
}
然后在滿足需求的控制器中調(diào)用即可。
方法如下:
override func viewDidLoad() {
super.viewDidLoad()
DH_MyViewController.nkReplaceSystemPresent()
}