我需要在用户关闭应用程序后立即显示本地通知(刷卡)。
为此,我有这样的代码:
- (void)applicationWillTerminate:(UIApplication *)application {
[self showNotificationAboutClosingApp];
}
和
- (void) showNotificationAboutClosingApp {
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = @"test title";
content.body = @"test body";
content.sound = UNNotificationSound.defaultSound;
NSString *requestIdentifier = [[NSUUID UUID] UUIDString];
NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:10.0];
NSDateComponents *components = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian] components:kCFCalendarUnitSecond fromDate:fireDate];
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:false];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier content:content trigger:trigger];
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
}
有一个奇怪的行为: 首次启动应用程序时,将其关闭(向上滑动)->通知将在10秒钟内出现。但是,当我重新打开应用程序并执行相同操作后,我的意思是通过向上滑动关闭应用程序,十秒钟后没有通知。我发现的结果-如果我从iPhone删除应用程序,然后关闭然后再次打开iPhone,安装应用程序,然后通过向上滑动关闭应用程序-出现通知。
任何想法我的方法有什么问题吗?
更新:
按照@MojtabaHosseini的建议,我将代码引导至这种类型:
//This class is the place where I prepare all stuff.
@objc class ClosingAppNotificationRequestProvider: NSObject {
@objc public static let shared = ClosingAppNotificationRequestProvider()
@objc public private(set) var closingAppNotificationRequest: UNNotificationRequest!
@objc public static var requestIdentifier: String {
get {
return UUID().uuidString
}
}
private override init() {}
@objc public func initialize() {
closingAppNotificationRequest = createClosingAppNotificationRequest()
}
private func createClosingAppNotificationRequest() -> UNNotificationRequest {
let content = UNMutableNotificationContent()
content.title = "some title";
content.body = "some body";
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let request = UNNotificationRequest(identifier: ClosingAppNotificationRequestProvider.requestIdentifier, content: content, trigger: trigger)
return request
}
}
然后发起请求
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[ClosingAppNotificationRequestProvider shared] initialize];
}
当应用终止时:
-(void)applicationWillTerminate:(UIApplication *)application {
UNNotificationRequest *closingAppNotificationRequest = [[ClosingAppNotificationRequestProvider shared] closingAppNotificationRequest];
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:closingAppNotificationRequest withCompletionHandler:nil];
}
但是结果确实一样。