首页 > 解决方案 > 通知权限问问题斯威夫特

问题描述

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

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()

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

标签: iosswiftxcode

解决方案


从文档

您的应用第一次发出此授权请求时,系统会提示用户批准或拒绝该请求,并记录用户的响应。后续授权请求不会提示用户。块引用

所以基本上你试图在他们已经被拒绝时请求权限:

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

你不能。authorizationStatus如果is ,您只能请求权限.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在授予或拒绝权限后重新测试状态,您需要卸载该应用程序。


推荐阅读