IOS 10.3 has opened up the API for changing app ICONS. The core method is as follows:
func setAlternateIconName(_ alternateIconName: String? .completionHandler: ((Error?). -> Void)? = nil)Copy the code
This is the official documentation, but you need to fill in the info.plist to make it work. The official comments are here.
However, how info.plist fills in this section is a bit confusing to read, so here’s an example.
<key>CFBundleIcons</key> <dict> <key>CFBundleAlternateIcons</key> <dict> <key>blackBgColor</key> <dict> <key>CFBundleIconFiles</key> <array> <string>blackBgColor</string> </array> <key>UIPrerenderedIcon</key> <false/> </dict> </dict> <key>CFBundlePrimaryIcon</key> <dict> <key>CFBundleIconFiles</key> <array> <string>AppIcon60x60</string> </array> </dict> </dict>Copy the code
As shown in the figure, the Primary Icon field is written as AppIcon60x60 because I only imported the image resources of 60pt@2x and 60pt@3x in xcassets here. It is selected as 60 because for iPhone, The 60pt image resource icon requires the highest quality, and the lower resolution version will be automatically compressed for display.
BlackBgColor is my image resource for replacing native ICONS. The file name needs to be the same as in info.plist (note that info.plist uses “blackBgColor” twice), and this is the parameter you need to pass to the API when setting ICONS in your code. For the same image resources as 60pt@2x and 60pt@3x, files are not added through assets. xcassets, but directly into the directory.
If you need to support the iPad, I suggest using the 83.5pt (iPad Pro) image resource here. There are a few other things to note about replacing ICONS on the iPad, which is explained here, but notice that the key we’ve used here in info.plist is CFBundleIcons, and another key is CFBundleIcons~ iPad.
Replacing the icon section of the code is super simple:
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func changeAppIcon(_ sender: Any) { 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 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 UIApplication.shared.setAlternateIconName("blackBgColor") { (err:Error?) In print("set icon error: \(String(err))")}}}}Copy the code
This is the full demo address for all of the above