Why [UNUserNotificationCenter currentNotificationCenter] fail [UNUserNotificationCenter currentNotificationCenter] ?
According to the failure stack trace, bundleIdentifier is nil in the UNUserNotificationCenter private initialization method, and an exception is thrown. I do not know why.
Unfortunately, the method is called in the context of dispatch_once , so we cannot easily reproduce this failure. At first I tried to use the NSBundle.mainBundle.bundleIdentifier : NSBundle.mainBundle.bundleIdentifier , but this failed. I assume that the system did not use this method to get bundleIdentifier, so I tried to use the private initialization method UNUserNotificationCenter initWithBundleIdentifier:(String) , it worked and tried to pass nil to this method, which caused a failure 100% of the time !! !! Therefore, we can use this method when downloading a file and return nil if bundleIdentifier==nil , I hope this helps you.

---------------- code -----------------
@implementation UNUserNotificationCenter (Hack) + (void)load { static dispatch_once_t _onceToken; dispatch_once(&_onceToken, ^{ [self safeHook]; }); } + (void)safeHook { NSString * orig_initWithBundleSelectorName = [NSString stringWithFormat:@"%@%@%@",@"initWi",@"thBundleId",@"entifier:"]; SEL orig_initWithBundleSelector = NSSelectorFromString(orig_initWithBundleSelectorName); if (![self instancesRespondToSelector:orig_initWithBundleSelector]) { return; } SEL alt_initWithBundleSelector = @selector(ht_initWithBundleIdentifier:); Method origMethod = class_getInstanceMethod(self, orig_initWithBundleSelector); Method altMethod = class_getInstanceMethod(self, @selector(ht_initWithBundleIdentifier:)); class_addMethod(self, orig_initWithBundleSelector, class_getMethodImplementation(self, orig_initWithBundleSelector), method_getTypeEncoding(origMethod)); class_addMethod(self, alt_initWithBundleSelector, class_getMethodImplementation(self, alt_initWithBundleSelector), method_getTypeEncoding(altMethod)); method_exchangeImplementations(origMethod, altMethod); } - (instancetype)ht_initWithBundleIdentifier:(id)identifier { if (nil==identifier||NSNull.null==identifier) { return nil; } return [self ht_initWithBundleIdentifier:identifier]; } @end
source share