iOS - 收到消息时触发本地通知

时间:2016-04-17 21:39:43

标签: ios objective-c uilocalnotification nsnotificationcenter

我正在构建一个应用程序,允许其用户发送彼此的消息。收到新消息时,它将显示在当前用户的“表”视图中。我希望我的应用在新消息到达时向当前用户发送通知。有谁知道我怎么可能这样做?

我已经在我的AppDelegate中设置了通知:

appdelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Let the device know we want to receive push notifications
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}

我知道以下代码将允许我在指定时间触发通知(例如,由选择器设置):

 // Get the current date
    NSDate *pickerDate = [self.datePicker date];

    // Schedule the notification
    UILocalNotification* localNotification = [[UILocalNotification alloc] init];
    localNotification.fireDate = pickerDate;
    localNotification.alertBody = self.itemText.text;
    localNotification.alertAction = @"You are being notified!";
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

    // Request to reload table view data
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:self];

    // Dismiss the view controller
    [self dismissViewControllerAnimated:YES completion:nil];

如果将新邮件发布到服务器(并显示在桌面视图中)以供登录用户使用,我该如何发出通知?

1 个答案:

答案 0 :(得分:0)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
       UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];}

如果您的系统是iOS8,则需要注册权限。

UILocalNotification * notification = [[UILocalNotification alloc] init];
    NSDate * pushDate = [NSDate dateWithTimeIntervalSinceNow:Time];
    if (notification!=nil) {


        notification.fireDate= pushDate;

        notification.timeZone = [NSTimeZone defaultTimeZone];

        notification.repeatInterval = kCFCalendarUnitDay;

        notification.soundName = UILocalNotificationDefaultSoundName;

        notification.alertBody = @"Time O.K!";
        NSLog(@"Ready");

        notification.applicationIconBadgeNumber = 1;
        //notification.applicationIconBadgeNumber = [[[UIApplication sharedApplication] scheduledLocalNotifications] count]+1;

        NSDictionary * inforDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
        notification.userInfo =inforDic;

        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }

您可以尝试一下,我可以在我的设备上成功使用此代码。