swift 本地通知、远程通知
无论是远程推送、本地推送都需要注册通知代码
iOS 8把原先一步到位的RemoteNotification的注册分成两部分,一部分是注册新引入的那个「UIUserNotificationSettings」,另一部分是RemoteNotifications。
事实上,Apple在iOS 8将RemoteNotification和LocalNotification统一了起来。两种Notifications将统一由UIUserNotificationSettings来管理用户界面相关的东西:标记、声音和提醒。除了统一用户界面的通知外,UIUserNotificationSettings还引入了UIUserNotificationCategory,可以让用户方便的直接在Notification上进行一些快捷的操作(Action)。
if(UIApplication.instancesRespondToSelector(Selector("registerUserNotificationSettings:"))){
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes:UIUserNotificationType.Sound |UIUserNotificationType.Alert |UIUserNotificationType.Badge, categories:nil))
}else{
application.registerForRemoteNotificationTypes(.Alert | .Sound | .Badge)
}
然后,在Appdelegate.swift 写相关远程推送、本地通知等代码
//收到本地通知
funcapplication(application:UIApplication, didReceiveLocalNotification notification:UILocalNotification) {
varalertView =UIAlertView(title:"系统本地通知", message: notification.alertBody, delegate:nil, cancelButtonTitle:"返回")
alertView.show()
}
//远程推送通知注册成功
funcapplication(application:UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken:NSData) {
println(deviceToken.description)
}
//远程推送通知注册失败
funcapplication(application:UIApplication, didFailToRegisterForRemoteNotificationsWithError error:NSError) {
iferror.code==3010{
println("Push notifications are not supported in the iOS Simulator.")
}else{
println("application:didFailToRegisterForRemoteNotificationsWithError:/(error)")
}
}
// 8.0之前收到远程推送通知
funcapplication(application:UIApplication, didReceiveRemoteNotification userInfo: [NSObject:AnyObject]) {
letnotif = userInfoasNSDictionary
letapsDic = notif.objectForKey("aps")asNSDictionary
letalertDic = apsDic.objectForKey("alert")asString
varalertView =UIAlertView(title:"系统本地通知", message: alertDic, delegate:nil, cancelButtonTitle:"返回")
alertView.show()
}
// 8.0之后收到远程推送通知
funcapplication(application:UIApplication, didReceiveRemoteNotification userInfo: [NSObject:AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) ->Void) {
letnotif = userInfoasNSDictionary
letapsDic = notif.objectForKey("aps")asNSDictionary
letalertDic = apsDic.objectForKey("alert")asString
varalertView =UIAlertView(title:"远程推送通知", message: alertDic, delegate:nil, cancelButtonTitle:"返回")
alertView.show()
}
//注册通知alert、sound、badge(8.0之后,必须要添加下面这段代码,否则注册失败)
funcapplication(application:UIApplication, didRegisterUserNotificationSettings notificationSettings:UIUserNotificationSettings) {
application.registerForRemoteNotifications()
}
******************************本地通知方法******************************
//
// TimeViewController.swift
// UIControlDemo
//
// Created byon 14/12/10.
// Copyright (c) 2014年马大哈. All rights reserved.
//
importUIKit
classTimeViewController:BaseViewController{
varwordTextField:UITextField?//文字
vardateTextField:UITextField?//时间
vardatePicker:UIDatePicker?
overridefuncviewDidLoad() {
super.viewDidLoad()
self.title="时间/日期/本地通知"
letleftBarButton:UIBarButtonItem=UIBarButtonItem(barButtonSystemItem: .Trash, target:self, action:"locaNotifcationDeleteAll")
self.navigationItem.rightBarButtonItem= leftBarButton;
wordTextField=UITextField(frame:CGRectMake(50,80,200,40))
wordTextField?.backgroundColor= .clearColor()
wordTextField!.tag=100
wordTextField?.borderStyle=UITextBorderStyle.RoundedRect
wordTextField?.keyboardType=UIKeyboardType.Default
wordTextField?.returnKeyType=UIReturnKeyType.Done
wordTextField?.contentVerticalAlignment=UIControlContentVerticalAlignment.Center
wordTextField?.clearButtonMode=UITextFieldViewMode.WhileEditing
wordTextField?.secureTextEntry=false
wordTextField?.textColor= .blackColor()
wordTextField?.textAlignment= .Left
wordTextField?.placeholder="键盘"
wordTextField?.font=UIFont.systemFontOfSize(15)
self.view.addSubview(wordTextField!)
dateTextField=UITextField(frame:CGRectMake(50,140,200,40))
dateTextField?.backgroundColor= .clearColor()
dateTextField!.tag=101
dateTextField?.borderStyle=UITextBorderStyle.RoundedRect
dateTextField?.keyboardType=UIKeyboardType.Default
dateTextField?.returnKeyType=UIReturnKeyType.Done
dateTextField?.contentVerticalAlignment=UIControlContentVerticalAlignment.Center
dateTextField?.textColor= .blackColor()
dateTextField?.textAlignment= .Left
dateTextField?.placeholder="日期picker"
dateTextField?.font=UIFont.systemFontOfSize(15)
self.view.addSubview(dateTextField!)
datePicker=UIDatePicker()
datePicker?.datePickerMode= .DateAndTime
datePicker?.timeZone=NSTimeZone.systemTimeZone()
datePicker?.addTarget(self, action:"datePickerSelected:", forControlEvents:UIControlEvents.ValueChanged)
dateTextField!.inputView=datePicker
varbutton =UIButton.buttonWithType(UIButtonType.Custom)asUIButton
button.frame=CGRectMake(200,200,50,30)
button.backgroundColor=UIColor.redColor()
button.setTitleColor(UIColor.blackColor(), forState:.Normal)
button.setTitle("保存", forState:UIControlState.Normal)
button.titleLabel!.font=UIFont.boldSystemFontOfSize(CGFloat(20))
button.showsTouchWhenHighlighted=true
button.addTarget(self, action:"saveLocalNotificationButton", forControlEvents:UIControlEvents.TouchUpInside)
self.view.addSubview(button)
}
// 保存按钮方法
funcsaveLocalNotificationButton(){
varcontentDic = ["KEY":"VALUE"]
locaNotifcationSchedule(chedulDate:datePicker!.date, alertBody:"通知看到:/(wordTextField!.text)", content: contentDic)
varalertView =UIAlertView(title:"保存成功", message:nil, delegate:nil, cancelButtonTitle:"返回")
alertView.show()
wordTextField?.resignFirstResponder()
dateTextField?.resignFirstResponder()
}
//注册本地通知
funclocaNotifcationSchedule(#chedulDate:NSDate,alertBody:String,content:NSDictionary) {
varlocalNotif =UILocalNotification()
localNotif.fireDate= chedulDate
localNotif.timeZone=NSTimeZone.defaultTimeZone()
// localNotif.repeatInterval = repeatInterval 0代表不重复
localNotif.soundName="iPhone.caf"//此属性可以不写(默认系统声音UILocalNotificationDefaultSoundName)
// localNotif.hasAction = true;
// localNotif.alertAction = "查看";
localNotif.alertBody= alertBody
localNotif.userInfo = content
UIApplication.sharedApplication().scheduleLocalNotification(localNotif)
}
//删除所有注册的本地通知
funclocaNotifcationDeleteAll() {
letapplication =UIApplication.sharedApplication()
application.cancelAllLocalNotifications()
varalertView =UIAlertView(title:"所有本地通知都已移除", message:nil, delegate:nil, cancelButtonTitle:"返回")
alertView.show()
}
//动态改变textfield内容
funcdatePickerSelected(datePicker:UIDatePicker){
letdateString =timeDateFormatter().stringFromDate(datePicker.date)
dateTextField!.text= dateString
}
overridefunctouchesEnded(touches:NSSet, withEvent event:UIEvent) {
wordTextField?.resignFirstResponder()
dateTextField?.resignFirstResponder()
}
overridefuncdidReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
优质内容筛选与推荐>>