App change icon

App change icon

On JD Taobao, every time it is 618 or Double Eleven, the app icon will be changed to fit the relevant theme, but the app has not been upgraded during that time, so there must be a configuration that can change the app icon.

I checked some documents and found the following method.

Prepare pictures

Prepare images in two sizes: 120x120 and 180x180. Named [email protected] and [email protected] respectively.

Then place the image in a directory of the project. Be careful not to put it in image assets .

Modify Info.plist

Open the project's Info.plist, right-click on the file, open as source code, and add the following code

<key>CFBundleIcons</key>
<dict>
    <key>CFBundleAlternateIcons</key>
    <dict>
        <key>NewAppIcon</key> // 这个是函数需要用到的参数
        <dict>
            <key>CFBundleIconFiles</key>
            <array>
                <string>icon</string> // 这个地方的icon就是文件名
            </array>
            <key>UIPrerenderedIcon</key>
            <false/>
        </dict>
    </dict>
</dict>

Add modify icon function

Add the following code to update.

if UIApplication.shared.supportsAlternateIcons {
    
    
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
    
    
        UIApplication.shared.setAlternateIconName("NewAppIcon") {
    
     error in
            if let error = error {
    
    
                print(error.localizedDescription)
            } else {
    
    
                print("Success!")
            }
        }
    }
}

After the update is completed, you will find that a prompt window pops up, which makes the experience not very good. So it needs to be modified slightly.
Add some methods.

func setApplicationIconName(_ iconName: String?) {
    
    
    if UIApplication.shared.responds(to: #selector(getter: UIApplication.supportsAlternateIcons)) && UIApplication.shared.supportsAlternateIcons {
    
    
        
        typealias setAlternateIconName = @convention(c) (NSObject, Selector, NSString?, @escaping (NSError) -> ()) -> ()
        
        let selectorString = "_setAlternateIconName:completionHandler:"
        
        let selector = NSSelectorFromString(selectorString)
        let imp = UIApplication.shared.method(for: selector)
        let method = unsafeBitCast(imp, to: setAlternateIconName.self)
        method(UIApplication.shared, selector, iconName as NSString?, {
    
     _ in })
    }
}

Use the above method when calling later.

if UIApplication.shared.supportsAlternateIcons {
    
    
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
    
    
        self.setApplicationIconName(nil)
    }
}

In this way, the icon can be changed silently.

Guess you like

Origin blog.csdn.net/xo19882011/article/details/135454649