swift 进入应用更新视图 NotificationCenter 传递数据更新视图

AooDelegate.swift

import UIKit


import Alamofire

import SwiftyJSON

    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        initNetData()
        return true
    }


    func applicationDidEnterBackground(_ application: UIApplication) {
        initNetData()

    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        
        initNetData()
  
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
    }

    func applicationWillTerminate(_ application: UIApplication) {
        initNetData()
    }

 

 func initNetData(){
      
        let operationQ = OperationQueue()
        let blockOp1 = BlockOperation()
        blockOp1.addExecutionBlock {
            let bundleId = Bundle.main.bundleIdentifier!
            let url = "xxx。com"
            
 
            Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {response in
                if let jsondata = response.data{
                 
                              let json = JSON(jsondata)
         
                    let show_ad = json["data"][0]["show_ad"] == "1" ? true:false
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "show_ad"), object: show_ad)
               
                   
                    
        
                }else{
                    print("输出失败")
                }
            })
            }
        
        operationQ.addOperation(blockOp1)
        
    }

在对应的vc种接受通知

    override func viewDidLoad() {
        super.viewDidLoad()

 
   
        NotificationCenter.default.addObserver(self, selector: #selector(initNavBar), name:NSNotification.Name(rawValue: "show_ad"),object: nil)
               
    }

 

    @objc func initNavBar(obj: NSNotification){
       let showAd =  obj.object as! Bool
      
        if showAd {
            self.navigationItem.leftBarButtonItems = [settingsItem, game]
        } else {

            self.navigationItem.leftBarButtonItems = [settingsItem]
        }
    }

 

你可能感兴趣的:(#,swift)