Мне нужно показывать локальное уведомление сразу после того, как пользователь закроет приложение (проведите пальцем вверх).
Для этого у меня есть такой код:
- (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 секунд появится уведомление.Но после того, как я снова открываю приложение и делаю то же самое, я имею в виду закрыть приложение с помощью пролистывания вверх, через 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];
}
Но на самом деле результат тот же.