布袋的世界之Apple苹果家园

系统权限设置 PermissionScope的使用方式及坑

2017-07-07  本文已影响56人  布袋的世界

这篇文章主要在吐槽bug,还有直接上代码的,
如果你刚要用,请转至简友入门基础篇:http://www.jianshu.com/p/c9aa0a0ae2c4
然后再来看这篇哦!

有些第三方库并不是完美的,甚至还有很多坑在等着你,比如 PermissionScope!
但虽然不完善,原理还有开源是非常值得我们去学习的!

先 pod 'PermissionScope',然后 ...

不多说了,直接上马了,先上二张图!


5DD41039-4329-4F21-BE70-81E97CBC0F36.png C45A0C5E-2A84-433E-967F-F5001F17E538.png

首先千千万万记得在 //using weak var by apiapia on 07/08/2017
不然,资源一下子就会节节往上的喔!

FIXME: on PermissionScope -> PermissionScope.swift

weak var weakSelf = self
viewControllerForAlerts = weakSelf

第一次装完APP,并进入通知设置viewController


不ALLOW.png

如果用户不同意,下次再进行设置时,直接引导用户到设置页面


allow.png
用户点击稍后,原生是nil的,下面是代码补充!
 let alert = UIAlertController(title: "前往开启\(permission.prettyDescription)权限".localized,
            message: "请点击·前往设置·开启 \(permission.prettyDescription) 权限".localized,
            preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "稍后".localized,style: .cancel,
                                      handler: { action in
                                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NSNotificationNameAlert"), object: nil, userInfo: ["permission":permission.prettyDescription])
        }))

接收通知

        // 观察者
        weak var weakSelf = self
        NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "NSNotificationNameAlert"), object: nil, queue: OperationQueue.main) { (key) in
            let permission = key.userInfo?["permission"] as! String
            print ("permission",permission)
            if permission == "Notifications" {
                print("关闭推送")
                weakSelf?.swtichAnnounce.isOn = false
            }else {
                print("关闭地理位置")
                weakSelf?.switchK3.isOn = false
            }
            
        }

记得移除通知

    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "NSNotificationNameAlert"), object: nil)
    }
vc.png

以下是代码

import UIKit
import MJRefresh
import SVProgressHUD
import Kingfisher
import PermissionScope
import CoreLocation

class MeVC:UITableViewController,ShareProtocol{
    
    fileprivate var permissionScopeManager:PermissionScope!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setTableView()
      
        // 观察者
        weak var weakSelf = self
        NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "NSNotificationNameAlert"), object: nil, queue: OperationQueue.main) { (key) in
            let permission = key.userInfo?["permission"] as! String
            print ("permission",permission)
            if permission == "Notifications" {
                print("关闭推送")
                weakSelf?.swtichAnnounce.isOn = false
            }else {
                print("关闭地理位置")
                weakSelf?.switchK3.isOn = false
            }
            
        }
    }

    @IBOutlet weak var swtichAnnounce: UISwitch!
    @IBOutlet weak var switchK3: UISwitch!
    // 推送设置
    @IBAction func switchAnounceTap(_ sender: UISwitch) {
         weak var weakSelf = self
         // print("switch推送位置开关:\(sender)")
        if sender.isOn {
            /// 请求通知权限
            permissionScopeManager.viewControllerForAlerts = weakSelf
            permissionScopeManager.requestNotifications()
            /// 监控通知权限,一旦用户点击允许或者拒绝,都会执行以下方法
            permissionScopeManager.onAuthChange =  { (finished, results) in
                
                print("通知:",weakSelf?.permissionScopeManager.statusNotifications() ?? "")
                let status = "\((weakSelf?.permissionScopeManager.statusNotifications())!)"
                switch status {
                case "Unauthorized" :
                    weakSelf?.swtichAnnounce.isOn = false
                    weakSelf?.swtichAnnounce.isEnabled = true
                    
                case "Authorized" :
                    weakSelf?.swtichAnnounce.isOn = true
                    weakSelf?.swtichAnnounce.isEnabled = false
                default :
                    print("")
                }
                
                weakSelf?.permissionScopeManager.viewControllerForAlerts?.dismiss(animated: false, completion: nil)
            }
            /// 获取当前的发送通知的权限状态
            let status = permissionScopeManager.statusNotifications()
            permissionScopeManager.onDisabledOrDenied = { results in
                print ("拒绝时候的results:\(results)")
                print ("通知权限被拒绝:\(status.description)")
                weakSelf?.swtichAnnounce.isOn = false
                weakSelf?.swtichAnnounce.isEnabled = true
            }
            if status == .authorized {
                weakSelf?.swtichAnnounce.isOn = true
                weakSelf?.swtichAnnounce.isEnabled = false
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
        else {
            // FIXME:调用系统设置 关闭权限
            
        }
    }
    // 地址位置分享
    @IBAction func switchK3Tap(_ sender: UISwitch) {
         weak var weakSelf = self
        // print("switch地址位置开关:\(sender)")
        if sender.isOn {
           permissionScopeManager.viewControllerForAlerts = weakSelf
           permissionScopeManager.requestLocationAlways()
            permissionScopeManager.onAuthChange =  { (finished,results) in
                print ("地理位置:\(weakSelf?.permissionScopeManager.statusLocationAlways())")
              
                let status = "\((weakSelf?.permissionScopeManager.statusLocationAlways())!)"
                switch status {
                case "Unauthorized" :
                    weakSelf?.switchK3.isOn = false
                    weakSelf?.switchK3.isEnabled = true
                    
                case "Authorized" :
                    weakSelf?.switchK3.isOn = true
                    weakSelf?.switchK3.isEnabled = false
                default :
                    print("返回地理位置")
                }
                
                weakSelf?.permissionScopeManager.viewControllerForAlerts?.dismiss(animated: false, completion: nil)
            }
            let status = permissionScopeManager.statusLocationAlways()
            if status == .authorized {
                weakSelf?.switchK3.isOn = true
                weakSelf?.switchK3.isEnabled = false 
            }
            permissionScopeManager.onDisabledOrDenied = { result in
                weakSelf?.switchK3.isOn = false
                weakSelf?.switchK3.isEnabled = true
            print ("地理位置权限被拒绝:\(status.description)")
            }
        }else {
            
        }
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //   navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "mine_settingIcon2", highlightedImage: "mine_settingIcon2_press", target: self, action: #selector(MeVC.settingClick))
        permissionScopeManager = PermissionScope.init(backgroundTapCancels:true)
        /// 设置弹出提示框的底层视图控制器
        initNotifications()

       
        
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "NSNotificationNameAlert"), object: nil)
    }
//    deinit {
//        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "NSNotificationNameAlert"), object: nil)
//    }
    // 通告 权限
    func initNotifications() {
        /// 初始化权限管理对象
        
        // 判断通知是否已开启
        switch permissionScopeManager.statusNotifications() {
        case .unknown:
            swtichAnnounce.isOn = false
            swtichAnnounce.isEnabled = true
           
        case .unauthorized,.disabled:
            swtichAnnounce.isOn = false
            swtichAnnounce.isEnabled = true
            //return
        case .authorized:
            swtichAnnounce.isOn = true
            swtichAnnounce.isEnabled = false
            //return
        }
        print ("PermissionScope().statusNotifications():\(permissionScopeManager.statusNotifications())")
        
        // 判断地理位置是否已开启
        switch permissionScopeManager.statusLocationAlways() {
        case .unknown :
            switchK3.isOn = false
            switchK3.isEnabled = true
           
        case .unauthorized,.disabled:
            switchK3.isOn = false
            switchK3.isEnabled = true
           // return
        case .authorized :
            switchK3.isOn = true
            switchK3.isEnabled = false
            //return
        }
        print ("PermissionScope().statusLocationAlways():\(permissionScopeManager.statusLocationAlways())")

    }
    
    // MARK: - 设置tableView
    func setTableView() {
        self.tableView.showsHorizontalScrollIndicator = false
        self.tableView.showsVerticalScrollIndicator = false
        self.tableView.sectionHeaderHeight = 0
        self.tableView.sectionFooterHeight = 10
        self.tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0)
        self.tableView.tableFooterView = UIView(frame: .zero)
        
    }

    // MARK: - 点击设置按钮
    func settingClick() {
        let settingVC = UIStoryboard(name: "SettingVC", bundle: nil).instantiateInitialViewController()!
        navigationController?.pushViewController(settingVC, animated: true)
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
        
        let section = indexPath.section
        let row = indexPath.row
        if section == 0 {
              // getAuthWithUserInfo(.sina) // print("新浪登陆")
                 getAuthWithUserInfo(.QQ) // 成功获取
                //getAuthWithUserInfo(UMSocialPlatformType.wechatSession)
  
        } else if section == 1 {
            
            if row == 0 {
                print("意见反馈")
            } else if row == 1 {
               // FIXME: 接入环信客服,服务器会保留信息,直接用电话? /* 联系客服*/
                 print("联系客服")
                let nextVC = UIStoryboard(name: "MySB", bundle: nil).instantiateViewController(withIdentifier: "KFSB")
                navigationController?.pushViewController(nextVC)
            }
            
        } else if section == 2 {
            /*protocoal 邀请好友*/
            if row == 0 { self.umengShareToAnother() }
            if row == 1 {print("商务合作")}
            if row == 2 {print("关于布袋")}
            
            
        } else if section == 3 {
            
        }
    }
 
}


// FIXME: -  第三方登录需把APP上传到官方进行审核,才可以接入,待营业执照来进行修复!
extension MeVC {
    func getAuthWithUserInfo(_ platformType:UMSocialPlatformType){
        UMSocialManager.default().getUserInfo(with: platformType, currentViewController: self) { (result, error) in
            if (error != nil) {
                print(error ?? "")
            }else{
                let resp: UMSocialUserInfoResponse? = result as! UMSocialUserInfoResponse?
                let uid = resp?.uid
                let username = resp?.name
                let iconurl = resp?.iconurl
                let gender  = resp?.gender
                print("第三方平台\(platformType),唯一ID:\(uid)昵称:\(username)头像:\(iconurl)性别\(gender)")
            }
            
        }
    }
 
}

重要的事情说三遍,最重要的一个BUG,最重要的一个BUG,最重要的一个BUG就是:有时点击后跳到设置页面,打开通知,返回APP ,会自动启动页广告,然后到了APP首页!

上面这个还没有修复...

上一篇下一篇

猜你喜欢

热点阅读