背景
电商项目总喜欢在特定节日展示不同的icon图标,但是为了修改图标而更新版本的话,没那个必要。
这里介绍一种不需要通过更新版本就可以动态修改APP图标的方法。
⚠️注意:该方法在iOS10.3及以上有效
实现
- 1 导入待替换的新图片,放到项目工程新文件夹中;
- 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 通过代码替换
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 恢复默认 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图标
UIApplication.shared.setAlternateIconName("icon1") { (err:Error?) in
print("set icon error:\(String(describing: err))")
}
}
}
- 4 去掉更换图标时的弹框
更换图标时会出现系统弹框,可以使用Runtime来隐藏弹框,这样方便在节日时候程序自动 无感 更改APP 的icon
具体代码如下:
extension UIViewController {
//通过运行时替换系统的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)
}
}
然后在满足需求的控制器中调用即可。
方法如下:
override func viewDidLoad() {
super.viewDidLoad()
DH_MyViewController.nkReplaceSystemPresent()
}
网友评论