我一直在寻找一个关于在Swift for iOS8中设置推送通知的正确教程,但我觉得从Objective-C到Swift和iOS7到iOS8已经做了很多改变,尽管我找不到任何更新了一段代码。
我想知道用户是否已经按下了“不允许"推送通知提醒中的按钮和/ 或者他们曾经看过它。
事实是,在这种情况下,我希望显示一条警告,要求用户通过设置实现通知。
问题:我不知道要检查哪个变量,以确定我是否应该显示弹出窗口。
我可以使用这个但是在两个从未显示1-推送通知警报的情况下,哈希值为0,显示了2-推送通知警报,但是用户已经按下了#34;不允许"。
if(UIApplication.sharedApplication().currentUserNotificationSettings().hashValue == 0){
pushNotificationStatus = "false"
} else {
pushNotificationStatus = "true"
}
您是否有任何最佳实践/想法来解决这个问题? 谢谢你!
答案 0 :(得分:0)
//Write belkow code in Appdelegate.m in didfinishLaunching mehod..
Register for Push Notitications, if running iOS 8
if application.respondsToSelector("registerUserNotificationSettings:") {
let types:UIUserNotificationType = (.Alert | .Badge | .Sound)
let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
// Register for Push Notifications before iOS 8
application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound)
}
你可以进入didFailToRegisterForRemoteNotificationsWithError
func application(
application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData
) {
//Process the deviceToken and send it to your server
let trimEnds = {
deviceToken.description.stringByTrimmingCharactersInSet(
NSCharacterSet(charactersInString: "<>"))
}
let cleanToken = {
trimEnds.stringByReplacingOccurrencesOfString(
" ", withString: "", options: nil)
}
}
func application(
application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: NSError
) {
//Log an error for debugging purposes, user doesn't need to know
NSLog("Failed to get token; error: %@", error)
}
在接收委托后的通知将致电:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
println("Recived: \(userInfo)")
//Parsing userinfo:
var temp : NSDictionary = userInfo
if let info = userInfo["aps"] as? Dictionary<String, AnyObject>
{
var alertMsg = info["alert"] as! String
var alert: UIAlertView!
alert = UIAlertView(title: "", message: alertMsg, delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
你可以控制UIApplication.sharedApplication()的哈希值.currentUserNotificationSettings()。
if(UIApplication.instancesRespondToSelector(Selector("registerUserNotificationSettings:"))){
if(UIApplication.sharedApplication().currentUserNotificationSettings().hashValue == 0){
pushNotificationStatus = "false"
} else {
pushNotificationStatus = "true"
}
}
答案 1 :(得分:0)
从iOS 10.0开始,您可以使用此方法
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { settings in
switch settings.authorizationStatus {
case .notDetermined:
print("Not determined")
case .denied: //In this case user has already seen this alert, and answered "Don't allow"
print("Denied")
case .authorized:
print("Authorised")
}