Skip to content

Instantly share code, notes, and snippets.

@piemonte
Created October 19, 2022 16:36
Show Gist options
  • Save piemonte/0abc34588df828070f672a83dcfc7e23 to your computer and use it in GitHub Desktop.
Save piemonte/0abc34588df828070f672a83dcfc7e23 to your computer and use it in GitHub Desktop.
//
// UIApplication+AppIcon.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2020-present patrick piemonte (http://patrickpiemonte.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import Foundation
extension UIApplication {
public enum AppIcon: String, CaseIterable, Identifiable {
case appIcon = "AppIcon"
case darkMode = "AppIcon-Dark"
public var id: String { rawValue }
var iconName: String? {
switch self {
case .appIcon:
return nil // reset app icon to initial state
default:
return rawValue
}
}
var description: String {
switch self {
case .appIcon:
return "Default"
case .darkMode:
return "Dark Mode"
}
}
var preview: UIImage {
UIImage(named: rawValue + "-Preview") ?? UIImage()
}
}
public enum AppIconError: Error {
case notSupported
}
public var selectedAppIcon: AppIcon {
guard UIApplication.shared.supportsAlternateIcons else {
return .appIcon
}
let selectedIconName = UIApplication.shared.alternateIconName
return AppIcon.allCases.first(where: {
$0.iconName == selectedIconName
}) ?? .appIcon
}
public func setAppIcon(appIcon: UIApplication.AppIcon, completionHandler: ((Swift.Result<String?, Error>) -> Void)?) {
guard UIApplication.shared.supportsAlternateIcons else {
DispatchQueue.main.async {
completionHandler?(.failure(AppIconError.notSupported))
}
return
}
self.setAlternateIconName(appIcon.iconName) { error in
if let error = error {
completionHandler?(.failure(error))
} else {
completionHandler?(.success(UIApplication.shared.alternateIconName))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment