Вот пример кода для LocalNotification , который работал для моего проекта.
Objective-C:
Этот блок кода в AppDelegate
файле:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
// Override point for customization after application launch.
return YES;
}
// This code block is invoked when application is in foreground (active-mode)
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
UIAlertView *notificationAlert = [[UIAlertView alloc] initWithTitle:@"Notification" message:@"This local notification"
delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[notificationAlert show];
// NSLog(@"didReceiveLocalNotification");
}
Этот блок кода в файле .m любого ViewController
:
-(IBAction)startLocalNotification { // Bind this method to UIButton action
NSLog(@"startLocalNotification");
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:7];
notification.alertBody = @"This is local notification!";
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
notification.applicationIconBadgeNumber = 10;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
Приведенный выше код отображает AlertView через 7 секунд после нажатия на кнопку, которая связывает startLocalNotification
Если приложение находится в фоновом режиме, тогда оно отображает BadgeNumber
как 10 и со звуком уведомления по умолчанию.
Этот код отлично работает для iOS 7.x и ниже, но для iOS 8 он выдаст следующую ошибку на консоли:
Попытка запланировать локальное уведомление с предупреждением, но пользователь не получил разрешение на отображение предупреждений
Это означает, что вам нужно зарегистрироваться для локального уведомления. Это может быть достигнуто с помощью:
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
Вы также можете обратиться blog для локального уведомления.
Swift:
Ваш AppDelegate.swift
файл должен выглядеть следующим образом:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert, categories: nil))
return true
}
Файл swift (скажем, ViewController.swift
), в котором вы хотите создать локальное уведомление, должен содержать следующий код:
//MARK: - Button functions
func buttonIsPressed(sender: UIButton) {
println("buttonIsPressed function called \(UIButton.description())")
var localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: 3)
localNotification.alertBody = "This is local notification from Swift 2.0"
localNotification.timeZone = NSTimeZone.localTimeZone()
localNotification.repeatInterval = NSCalendarUnit.CalendarUnitMinute
localNotification.userInfo = ["Important":"Data"];
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.applicationIconBadgeNumber = 5
localNotification.category = "Message"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
//MARK: - viewDidLoad
class ViewController: UIViewController {
var objButton : UIButton!
. . .
override func viewDidLoad() {
super.viewDidLoad()
. . .
objButton = UIButton.buttonWithType(.Custom) as? UIButton
objButton.frame = CGRectMake(30, 100, 150, 40)
objButton.setTitle("Click Me", forState: .Normal)
objButton.setTitle("Button pressed", forState: .Highlighted)
objButton.addTarget(self, action: "buttonIsPressed:", forControlEvents: .TouchDown)
. . .
}
. . .
}
То, как вы используете работу с локальными уведомлениями в iOS 9 и ниже, совершенно отличается в iOS 10.
Ниже приведен скриншот из заметок о выпуске Apple.

Вы можете обратиться справочный документ Apple для UserNotification.
Ниже приведен код для локального уведомления:
Objective-C:
В App-delegate.h
использовании файла @import UserNotifications;
Делегат приложения должен соответствовать UNUserNotificationCenterDelegate
протоколу
В didFinishLaunchingOptions
используйте следующий код:
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
[self showAlert];
}
}];
-(void)showAlert {
UIAlertController *objAlertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"show an alert!" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK"
style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
NSLog(@"Ok clicked!");
}];
[objAlertController addAction:cancelAction];
[[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YES completion:^{
}];
}
Теперь создайте кнопку в любом контроллере вида и в IBAction используйте следующий код:
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@“Notification!” arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@“This is local notification message!“arguments:nil];
objNotificationContent.sound = [UNNotificationSound defaultSound];
// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
// Deliver the notification in five seconds.
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10.f repeats:NO];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@“ten” content:objNotificationContent trigger:trigger];
// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(@“Local Notification succeeded“);
} else {
NSLog(@“Local Notification failed“);
}
}];
Swift 3:
- В
AppDelegate.swift
использование файла import UserNotifications
- Приложение должно соответствовать протоколу
UNUserNotificationCenterDelegate
В didFinishLaunchingWithOptions
используйте ниже код
// Override point for customization after application launch.
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
if error != nil {
print("Request authorization failed!")
} else {
print("Request authorization succeeded!")
self.showAlert()
}
}
func showAlert() {
let objAlert = UIAlertController(title: "Alert", message: "Request authorization succeeded", preferredStyle: UIAlertControllerStyle.alert)
objAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
//self.presentViewController(objAlert, animated: true, completion: nil)
UIApplication.shared().keyWindow?.rootViewController?.present(objAlert, animated: true, completion: nil)
}
Теперь создайте кнопку в любом контроллере вида и в IBAction используйте следующий код:
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "notify-test"
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
let request = UNNotificationRequest.init(identifier: "notify-test", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request)