通知权限询问问题Swift



我是通知权限授予和检查设置的新手,如果我检查了设置是否被拒绝或未确定,我就实现了权限授予,我的代码似乎不起作用,它没有错误,但它只是没有显示请求授予权限的窗口:

import UIKit
import UserNotifications
import Alamofire
import SwiftyJSON
class HomePageViewController: UIViewController {

@IBOutlet weak var userName: UILabel!

let content = UNMutableNotificationContent()

override func viewDidLoad() {
super.viewDidLoad()
// notification create:
userName.text = "Welcome! (MyVariables.username)"
let center = UNUserNotificationCenter.current()

center.getNotificationSettings(completionHandler: { settings in
if(settings.authorizationStatus == .denied || settings.authorizationStatus == .notDetermined){
print("not granted or denied")
center.requestAuthorization(options: [.alert, .sound])
{(granted, error) in
}
}
})
getRequest()
// Do any additional setup after loading the view.
}

// the function that get Request from the API
func getRequest(){

let params: [String:Any] = ["username": MyVariables.username]
// print(MyVariables.username)
AF.request("url", method: .post, parameters: params, encoding: JSONEncoding.default)
.responseJSON { (response) in
do{
print(String(data: response.data!, encoding: .utf8))
let json = try JSON(data: response.data!)
var flag: Bool = false
var countor: Int = 1
// if it has trigger pulling:
var info:String = ""

while json[String(countor)]["message"].stringValue != ""{
print("reached")
flag = true
info += json[String(countor)]["message"].stringValue
if(json[String(countor + 1)]["message"].stringValue != ""){
countor += 1
info += "n"
} else {
break
}

}
if(flag){
let center = UNUserNotificationCenter.current()
self.content.title = "Trigger(s) pulled"
self.content.body = info
self.content.sound = UNNotificationSound.default
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: self.content, trigger: nil)
center.add(request) { (error) in
print(error ?? "")
}
// send alert window:
self.createAlert(title: " trigger(s) pulled",
message: "You have (countor) triggers pulled: n (info)")
// reinitialize flag back to false
flag = false
}
// notification
//                            if(1 == 0){
//                                self.createAlert(title: " ", message: "The triger pulled")
//                            }
} catch let jsonErr{
print(jsonErr)
}

// Trigger a new request 5s after the response
DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: { [weak self] in
self?.getRequest()
})
}
}

func createAlert(title: String, message: String){
let Alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
Alert.addAction(UIAlertAction(title: "ok", style: UIAlertAction.Style.default, handler: { (action) in
Alert.dismiss(animated: true, completion: nil)
}))
self.present(Alert, animated: true, completion: nil)
}

/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}

在测试案例中,我关闭了模拟器设置中的通知

我的控制台是这样的:

not granted or denied
nil
Optional("{}n")

这意味着我检查了权限是否未被授予,但我没有看到任何窗口,错误消息似乎为零,最后一条是执行getRequest((

还有一个问题,如代码所示,如果我需要在getRequest((中使用中心变量来推送通知请求,那么除了viewDidload((中的一个之外,我在getRequest中声明另一个可以吗?或者,我应该在这些方法之外的类中拥有全局变量,并通过self.center调用它们吗?

来自文档:

当您的应用程序首次提出此授权请求时,系统会提示用户批准或拒绝该请求,并记录用户的响应。后续的授权请求不会提示用户。区块报价

因此,基本上,当权限已经被拒绝时,您正在尝试请求权限:

if(settings.authorizationStatus == .denied || settings.authorizationStatus == .notDetermined){
print("not granted or denied")
center.requestAuthorization(options: [.alert, .sound]){ (granted, error) in
}
}

你不能。只有当authorizationStatus.notDetermined时,才能请求权限。这个答案描述了最佳策略:

let current = UNUserNotificationCenter.current()
current.getNotificationSettings(completionHandler: { (settings) in
if settings.authorizationStatus == .notDetermined {
print("not granted yet - ask the user")
center.requestAuthorization(options: [.alert, .sound]){ (granted, error) in
guard error == nil && granted else {
print("User denied permissions, or error occurred")
return
}
print("permissions granted")
}
} else if settings.authorizationStatus == .denied {
print("Notification permission was previously denied, tell the user to go to settings & privacy to re-enable")
} else if settings.authorizationStatus == .authorized {
print("Notification permission was already granted")
}
})

如果您想在授予或拒绝权限后重新测试.notDetermined状态,则需要卸载该应用程序。

最新更新