1
我很努力讓推送通知與iOS 10的Swift一起使用。註冊似乎正在成功完成,但創建通知不會在設備上執行任何操作,並返回零錯誤。任何想法我失蹤?Swift iOS 10的推送通知
import Foundation
import UIKit
import UserNotifications
class SPKPushNotifications
{
class func register(application:UIApplication){
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
application.registerForRemoteNotifications()
}
} else {
let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound]
let pushNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil)
application.registerUserNotificationSettings(pushNotificationSettings)
application.registerForRemoteNotifications()
}
}
class func unregister(application:UIApplication){
application.unregisterForRemoteNotifications()
}
class func create(title:String, body:String, delay:Double, repeats:Bool){
if #available(iOS 10.0, *) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default() //idk if we're gonna want something else
content.badge = NSNumber(value:UIApplication.shared.applicationIconBadgeNumber+1)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval:delay, repeats:repeats)
let request = UNNotificationRequest(identifier:title, content:content, trigger:trigger)
let center = UNUserNotificationCenter.current()
center.add(request){ (error) in
print(error)
}
} else {
// Fallback on earlier versions
}
}
class func delete(){
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.removeAllDeliveredNotifications()
} else {
// Fallback on earlier versions
}
}
}
延遲10秒不起作用。有沒有辦法通過代碼將應用程序移動到背景? – Dominic
好的,所以我可以使用'UIApplication.shared.perform(#selector(URLSessionTask.suspend))'將應用程序移動到背景,並顯示通知。但我不想將應用程序移到後臺。我希望它在添加通知時保持打開狀態。 – Dominic
您可以通過點擊主頁按鈕將應用程序移動到設備的背景上,在模擬器中您可以使用硬件 - >主頁。 如果您的應用程序不在前臺,則通知旨在讓用戶可見。如果你的應用程序在前臺,爲什麼你需要通過通知來通知他們,你可以在應用程序中使用UI。也許你可以詳細闡述你的用例。但是,這似乎是另一個問題,因爲你的推送通知現在正在工作。 – little