如何创建本地通知? [英] How to create local notifications?

查看:80
本文介绍了如何创建本地通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置本地通知,以便在设置时,我的应用程序会生成带有自定义消息的通知/警报?

How can I setup local notifications so that at the time I set, my app generates a notification/alert with a customized message?

推荐答案

以下是适用于我的项目的 LocalNotification 的示例代码.

Here is sample code for LocalNotification that worked for my project.

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");
    }

任何ViewController的.m文件中的此代码块:

This code block in .m file of any 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];    
}

上面的代码在按绑定了startLocalNotification的按钮时,在7秒的时间间隔后显示AlertView.如果应用程序在后台,则它将BadgeNumber显示为10,并带有默认通知声音.

The above code display an AlertView after time interval of 7 seconds when pressed on button that binds startLocalNotification If application is in background then it displays BadgeNumber as 10 and with default notification sound.

此代码在iOS 7.x及更低版本上正常运行,但在 iOS 8上,它将在控制台上提示以下错误:

This code works fine for iOS 7.x and below but for iOS 8 it will prompt following error on console:

尝试安排带有警报的本地通知,但尚未获得用户显示警报的权限

Attempting to schedule a local notification with an alert but haven't received permission from the user to display alerts

这意味着您需要注册以获取本地通知.可以使用以下方法实现:

This means you need register for local notification. This can be achieved using:

if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){

    [application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}

您也可以参考博客本地通知.

You can also refer blog for local notification.

快捷键:

您的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
}

您要在其中创建本地通知的快捷文件(例如ViewController.swift)应包含以下代码:

The swift file (say ViewController.swift) in which you want to create local notification should contain below code:

//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发行说明中的​​屏幕截图对此进行了描述.

Below screen grab from Apple release notes depicts this.

您可以参考苹果参考文档以获得UserNotification.

You can refer apple reference document for UserNotification.

以下是本地通知的代码:

Objective-C:

  1. App-delegate.h文件中使用@import UserNotifications;

App-delegate应该符合UNUserNotificationCenterDelegate协议

App-delegate should conform to UNUserNotificationCenterDelegate protocol

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中使用以下代码:

  • Now create a button in any view controller and in IBAction use below code :

    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");
        }
    }];
    

  • 快捷键3:

    1. AppDelegate.swift文件中使用import UserNotifications
    2. Appdelegate应该符合UNUserNotificationCenterDelegate协议
    3. didFinishLaunchingWithOptions中使用以下代码

    1. In AppDelegate.swift file use import UserNotifications
    2. Appdelegate should conform to UNUserNotificationCenterDelegate protocol
    3. In didFinishLaunchingWithOptions use below code

    // 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中使用以下代码:

  • Now create a button in any view controller and in IBAction use below code :

    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)
    

  • 这篇关于如何创建本地通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆