背景
項目開發(fā)過程中营密,可能會有更換項目圖標的需求,比如一些電商的應(yīng)用目锭,在雙11,618纷捞,新年等節(jié)日的時候需要顯示特定的圖標痢虹,但如果單單為了修改圖標就要更新新版本的話,感覺有點得不償失主儡。這里介紹一種不需要通過更新版本就可以動態(tài)修改APP圖標的方法奖唯。
注意:該方法在iOS10.3及以上有效
實現(xiàn)
- 導(dǎo)入待替換的新圖片,不要放在Assets中糜值,放到項目工程中丰捷;
- 配置 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>
<key>icon3</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>icon3</string>
</array>
<key>UIPrerenderedIcon</key>
<false/>
</dict>
</dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon60x60</string>
</array>
</dict>
</dict>
- 通過代碼替換
- (void)changeAppIconWithName:(NSString *)iconName {
if (![[UIApplication sharedApplication] supportsAlternateIcons]) {
return;
}
if ([iconName isEqualToString:@""]) {
iconName = nil;
}
[[UIApplication sharedApplication] setAlternateIconName:iconName completionHandler:^(NSError * _Nullable error) {
if (error) {
NSLog(@"更換app圖標發(fā)生錯誤了 : %@",error);
}
}];
}
-
去掉更換圖標時的彈框
更換圖標時會出現(xiàn)如下彈框,可以使用Runtime來隱藏彈框
彈框.jpg
具體代碼:
#import "UIViewController+Category.h"
#import <objc/runtime.h>
@implementation UIViewController (Category)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method presentM = class_getInstanceMethod(self.class, @selector(presentViewController:animated:completion:));
Method presentSwizzlingM = class_getInstanceMethod(self.class, @selector(dismissAlertViewController:animated:completion:));
//runtime方法交換寂汇,通過攔截彈框事件,實現(xiàn)方法轉(zhuǎn)換,從而去掉彈框
method_exchangeImplementations(presentM, presentSwizzlingM);
});
}
- (void)dismissAlertViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)animated completion:(void (^)(void))completion {
if ([viewControllerToPresent isKindOfClass:[UIAlertController class]]) {
UIAlertController *alertController = (UIAlertController *)viewControllerToPresent;
if (alertController.title == nil && alertController.message == nil) {
return;
}
}
[self dismissAlertViewController:viewControllerToPresent animated:animated completion:completion];
}
@end
說明
- 替換的方法不要直接放在didFinishLaunchingWithOptions 或者viewDidLoad里面病往,如果要放的話,給替換的圖標的方法加個延時骄瓣。
- 替換的圖標并不需要上傳多張停巷,上傳一張就可以了,不過不要太小,