天天看點

iOS10通知(二)--發送通知

在新版本的通知架構中,蘋果采用網絡請求的風格,我們發送一個通知請求,然後将這個請求送出給UNUserNotificationCenter進行處理,然後我們會在 delegate 中接收到這個通知請求對應的 response,另外我們也可以在應用的 extension 中對 request 進行處理。

1、下面是發送通知的實作代碼段,此處實作的是一個延時發送的通知類型,有興趣的可以自行實作餘下的兩種類型UNCalendarNotificationTrigger和UNLocationNotificationTrigger

-(void)btnClicked
{
    //收起鍵盤
    [self.timeField resignFirstResponder];
    
    //判斷文本框的值是否有效
    NSInteger timeValue = [self.timeField.text integerValue];
    if(timeValue > 0)
    {
        self.label2.text = @"";
        
        //建立通知
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc]init];
        content.title = @"iOS 10通知";
        content.body = @"這是一個iOS 10的消息通知...";
        
        //建立一個觸發事件
        UNNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:timeValue repeats:NO];
        
        //設定通知的唯一辨別
        NSString *requestIdentifer = @"timeIntervalNotification";
        
        //建立通知的請求
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifer content:content trigger:trigger];
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            if (!error) {
                self.label2.text = error.localizedDescription;
            }
            else
            {
                self.label2.text = @"發送成功...";
            }
        }];
    }
    else
    {
        self.label2.text = @"輸入的時間無效";
    }
}           

2、遠端推送的payload内容

{
  "aps":{
    "alert":{
      "title":"iOS 10通知",
      "body":"這是一個iOS 10的消息通知..."
    }
  }
}           

3、下面是實作後的效果圖,從效果圖可以看到,不管應用是在前台還是背景,均可收到通知提示

iOS10通知(二)--發送通知
iOS10通知(二)--發送通知