无论是远程推送、本地推送 都需要注册通知代码
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 写相关远程推送、本地通知等代码
// 收到本地通知
func application(application: UIApplication , didReceiveLocalNotification notification: UILocalNotification ) {
var alertView = UIAlertView (title: " 系统本地通知 " , message: notification. alertBody , delegate: nil , cancelButtonTitle: " 返回 " )
alertView. show ()
}
// 远程推送通知 注册成功
func application(application: UIApplication , didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData ) {
println (deviceToken. description )
}
// 远程推送通知 注册失败
func application(application: UIApplication , didFailToRegisterForRemoteNotificationsWithError error: NSError ) {
if error. code == 3010 {
println ( "Push notifications are not supported in the iOS Simulator." )
} else {
println ( "application:didFailToRegisterForRemoteNotificationsWithError: /(error) " )
}
}
// 8.0 之前 收到远程推送通知
func application(application: UIApplication , didReceiveRemoteNotification userInfo: [ NSObject : AnyObject ]) {
let notif = userInfo as NSDictionary
let apsDic = notif. objectForKey ( "aps" ) as NSDictionary
let alertDic = apsDic. objectForKey ( "alert" ) as String
var alertView = UIAlertView (title: " 系统本地通知 " , message: alertDic, delegate: nil , cancelButtonTitle: " 返回 " )
alertView. show ()
}
// 8.0 之后 收到远程推送通知
func application(application: UIApplication , didReceiveRemoteNotification userInfo: [ NSObject : AnyObject ], fetchCompletionHandler completionHandler: ( UIBackgroundFetchResult ) -> Void ) {
let notif = userInfo as NSDictionary
let apsDic = notif. objectForKey ( "aps" ) as NSDictionary
let alertDic = apsDic. objectForKey ( "alert" ) as String
var alertView = UIAlertView (title: " 远程推送通知 " , message: alertDic, delegate: nil , cancelButtonTitle: " 返回 " )
alertView. show ()
}
// 注册通知 alert 、 sound 、 badge ( 8.0 之后,必须要添加下面这段代码,否则注册失败)
func application(application: UIApplication , didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings ) {
application. registerForRemoteNotifications ()
}
****************************** 本地通知方法 ********** ***** ***************
//
// TimeViewController.swift
// UIControlDemo
//
// Created by on 14/12/10.
// Copyright (c) 2014 年 马大哈 . All rights reserved.
//
import UIKit
class TimeViewController: BaseViewController {
var wordTextField: UITextField ? // 文字
var dateTextField: UITextField ? // 时间
var datePicker: UIDatePicker ?
override func viewDidLoad() {
super . viewDidLoad ()
self . title = " 时间 / 日期 / 本地通知 "
let leftBarButton: 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
var button = UIButton . buttonWithType ( UIButtonType . Custom ) as UIButton
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)
}
// 保存按钮方法
func saveLocalNotificationButton(){
var contentDic = [ "KEY" : "VALUE" ]
locaNotifcationSchedule (chedulDate: datePicker !. date , alertBody: " 通知看到 : /( wordTextField !. text ) " , content: contentDic)
var alertView = UIAlertView (title: " 保存成功 " , message: nil , delegate: nil , cancelButtonTitle: " 返回 " )
alertView. show ()
wordTextField ?. resignFirstResponder ()
dateTextField ?. resignFirstResponder ()
}
// 注册本地通知
func locaNotifcationSchedule(#chedulDate: NSDate ,alertBody: String ,content: NSDictionary ) {
var localNotif = 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)
}
// 删除所有注册的本地通知
func locaNotifcationDeleteAll() {
let application = UIApplication . sharedApplication ()
application. cancelAllLocalNotifications ()
var alertView = UIAlertView (title: " 所有本地通知都已移除 " , message: nil , delegate: nil , cancelButtonTitle: " 返回 " )
alertView. show ()
}
// 动态改变 textfield 内容
func datePickerSelected(datePicker: UIDatePicker ){
let dateString = timeDateFormatter (). stringFromDate (datePicker. date )
dateTextField !. text = dateString
}
override func touchesEnded(touches: NSSet , withEvent event: UIEvent ) {
wordTextField ?. resignFirstResponder ()
dateTextField ?. resignFirstResponder ()
}
override func didReceiveMemoryWarning() {
super . didReceiveMemoryWarning ()
}
}