【发布时间】:2021-02-23 20:29:41
【问题描述】:
我是通知权限授予和检查设置的新手,如果我检查设置被拒绝或未确定,我实施了权限授予,我的代码似乎不起作用,它没有错误但它没有显示请求授予权限的窗口:
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.
}
*/
}
在测试用例中,我在anmulator的设置中关闭了通知
这是我的控制台的外观:
not granted or denied
nil
Optional("{}\n")
这意味着我检查了权限未授予但我没有看到任何窗口并且错误消息似乎为零,最后一个是执行 getRequest()
还有一个问题,如代码所示,如果我需要使用中心变量在getRequest()中推送通知请求,我在getRequest()中声明另一个是否可以,除了viewDidload()中的一个?或者我应该在这些方法之外的类中拥有全局变量并通过 self.center 调用它们?
【问题讨论】:
-
如果通知权限已被用户明确拒绝,则不会显示权限提示。权限提示仅在用户未做出选择(允许或拒绝)时显示。显示提示并且用户做出选择后,只能由用户进入设置来修改权限。该应用不再有机会请求权限