//MARK:發(fā)起通知
func scheduleNotification(itemID:Int){
//如果已存在該通知消息,則先取消
cancelNotification(itemID: itemID)
//創(chuàng)建UILocalNotification來進行本地消息通知
let localNotification = UILocalNotification()
//推送時間(設(shè)置為30秒以后)
localNotification.fireDate = Date(timeIntervalSinceNow: 6)
//時區(qū)
localNotification.timeZone = NSTimeZone.default
//推送內(nèi)容
localNotification.alertBody = "您已超出圍欄區(qū)域"
// 2.7.設(shè)置有通知時的音效
localNotification.soundName = "126.wav"
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
//聲音
//? ? ? ? localNotification.soundName = UILocalNotificationDefaultSoundName
//額外信息
localNotification.userInfo = ["ItemID":itemID]
UIApplication.shared.scheduleLocalNotification(localNotification)
}
//取消通知消息
func cancelNotification(itemID:Int){
//通過itemID獲取已有的消息推送,然后刪除掉,以便重新判斷
let existingNotification = self.notificationForThisItem(itemID: itemID)
if existingNotification != nil {
//如果existingNotification不為nil,就取消消息推送
UIApplication.shared.cancelLocalNotification(existingNotification!)
}
}
//通過遍歷所有消息推送,通過itemid的對比,返回UIlocalNotification
func notificationForThisItem(itemID:Int)-> UILocalNotification? {
let allNotifications = UIApplication.shared.scheduledLocalNotifications
for notification in allNotifications! {
let info = notification.userInfo as! [String:Int]
let number = info["ItemID"]
if number != nil && number == itemID {
return notification as UILocalNotification
}
}
return nil
}
//MARK:發(fā)起通知
func FaQiTongZhi() -> () {
// 1.創(chuàng)建本地通知
let localNote = UILocalNotification()
// 2.設(shè)置本地通知的內(nèi)容
// 2.1.設(shè)置通知發(fā)出的時間
localNote.fireDate! = NSDate(timeIntervalSinceNow: 1.0) as Date
// 2.2.設(shè)置通知的內(nèi)容
localNote.alertBody! = "超出圍欄"
// 2.3.設(shè)置滑塊的文字(鎖屏狀態(tài)下:滑動來“解鎖”)
localNote.alertAction! = "解鎖"
// 2.4.決定alertAction是否生效
localNote.hasAction = false
// 2.5.設(shè)置點擊通知的啟動圖片
localNote.alertLaunchImage! = "icon_huodong"
// 2.6.設(shè)置alertTitle
if #available(iOS 8.2, *) {
localNote.alertTitle = "你有一條新通知"
} else {
// Fallback on earlier versions
//? ? ? ? ? ? localNote.alertBody = "你有一條新通知"
}
// 2.7.設(shè)置有通知時的音效
localNote.soundName! = "8308.wav"
// 2.8.設(shè)置應用程序圖標右上角的數(shù)字
localNote.applicationIconBadgeNumber = 1
// 2.9.設(shè)置額外信息
localNote.userInfo! = ["type": 1]
// 3.調(diào)用通知
UIApplication.shared.scheduleLocalNotification(localNote)
}