UserDefaults data not removed when mac OS X app is removed/moved to bin

We have an enterprise mac OS X application which uses the UserDefaults to store the onboarding states. The strange part here is that the newly installed mac OS X app is still be able to access the UserDefalus data of removed application. Because of this, the application never becomes as a freshly installed app. Is it any limitation to Enterprise mac OS X apps? Could you please provide us the resolution for this issue.

Answered by DTS Engineer in 834967022

This is expected behaviour for all apps on macOS. The fundamental issue here is that macOS is substantially more flexible than iOS, and thus there’s no good way to tell if an app has been deleted. See this post for more details.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

1.检测应用是否为新安装 通过检查应用程序包的创建日期是否与之前记录的日期不同,判断是否为重新安装。

2.清除UserDefaults数据 如果检测到新安装,则清除所有UserDefaults数据,并存储当前安装日期。 代码实现(Swift):func handleFreshInstall() { let defaults = UserDefaults.standard guard let bundleIdentifier = Bundle.main.bundleIdentifier else { return }

do {
let bundlePath = Bundle.main.bundlePath
let attributes = try FileManager.default.attributesOfItem(atPath: bundlePath)
guard let currentInstallDate = attributes[.creationDate] as? Date else {
return
}
let key = "appInstallDate"
if let storedInstallDate = defaults.object(forKey: key) as? Date {
if currentInstallDate != storedInstallDate {
// 检测到重新安装,清除数据

handleFreshInstall() defaults.set(currentInstallDate, forKey: key) defaults.synchronize() // 执行其他初始化设置 print("UserDefaults已重置") } } else { // 首次运行,保存安装日期 defaults.set(currentInstallDate, forKey: key) } } catch { print("获取属性失败: (error)") } }

// 在应用启动时调用该方法 handleFreshInstall()
步骤解释:

获取应用安装日期:使用FileManager获取应用程序包的创建日期,该日期在每次重新安装时会更新。

比较安装日期:将当前安装日期与之前存储在UserDefaults中的日期对比。

重置数据:若日期不同,则清除UserDefaults并存储新日期,确保后续启动不会重复清除。

首次运行处理:若未存储过日期,则保存当前日期,避免首次安装时误删数据。

注意事项:

企业应用更新:若通过企业渠道更新应用(版本升级),安装日期会变化,导致用户数据被重置。若需保留数据,需结合版本号检查,仅在版本未变且安装日期变化时重置。

测试验证:在不同macOS版本和安装方式下测试,确保创建日期的准确性。

替代方案:

使用钥匙串存储唯一标识:生成UUID存储于钥匙串,即使应用删除仍可检测是否为全新安装。但需处理钥匙串的访问权限。

引导用户手动清除:在应用内提供“重置数据”选项,或指导用户删除~/Library/Preferences/<bundle-id>.plist文件。

This is expected behaviour for all apps on macOS. The fundamental issue here is that macOS is substantially more flexible than iOS, and thus there’s no good way to tell if an app has been deleted. See this post for more details.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

UserDefaults data not removed when mac OS X app is removed/moved to bin
 
 
Q