TabBarController.swift 6.85 KB
//
//  TabBarController.swift
//  ParentAssistant
//
//  Created by 葛建军 on 2018/3/8.
//  Copyright © 2018年 HANGZHOUTEAM. All rights reserved.
//

import UIKit

class TabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        updataVersion()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // 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.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    func updataVersion(_ isRemain:Bool=false){
        let request = NSMutableURLRequest(url: URL(string: "http://itunes.apple.com/lookup?id=1357945086")!, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 10)
        request.httpMethod = "POST"
        //        NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main, completionHandler: { (respones, data, error) in
        let config=URLSessionConfiguration.default
        let session=URLSession(configuration: config, delegate: self, delegateQueue: nil)
        let dataTask=session.dataTask(with: request as URLRequest, completionHandler: { (data, response, sessionError) in
            if let datas = data{
                do{
                    let dictionary = try JSONSerialization.jsonObject(with: datas, options: JSONSerialization.ReadingOptions.mutableLeaves)
                    if ((dictionary as! NSDictionary)["resultCount"] as AnyObject).int32Value > 0{
                        let dataInformatica = ((dictionary as! NSDictionary)["results"] as! NSArray)[0] as! NSDictionary
                        let version = dataInformatica["version"]! as! String
                        if UIApplication.appVersion() < version{
                            let alert = UIAlertController(title: "发现新版本", message: dataInformatica["releaseNotes"]! as? String, preferredStyle: .alert)
                            alert.addAction(UIAlertAction(title: "前往更新", style: .default, handler: { (action) in
                                if #available(iOS 10.0, *) {
                                    UIApplication.shared.open(URL(string: "itms-apps://itunes.apple.com/app/id1357945086")!, options: [:], completionHandler: nil)
                                } else {
                                    // Fallback on earlier versions
                                    UIApplication.shared.openURL(URL(string: "itms-apps://itunes.apple.com/app/id1271291794")!)
                                }
                            }))
                            alert.addAction(UIAlertAction(title: "以后再说", style: .cancel, handler: { (action) in
                                
                            }))
                            self.present(alert, animated: true, completion: nil)
                        }else{
                            if isRemain{
                                appDelegate.window?.makeToast("已经是最新版本")
                            }
                            NSLog("不需要更新")
                        }
                    }
                }
                catch let error as NSError {
                    NSLog("请求失败")
                    appDelegate.window?.makeToast(error.localizedDescription)
                }
            }
        })
        dataTask.resume()
    }
}
extension TabBarController: URLSessionDelegate {
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        //认证服务器证书
        if challenge.protectionSpace.authenticationMethod
            == (NSURLAuthenticationMethodServerTrust) {
            print("服务端证书认证!")
            completionHandler(.performDefaultHandling, nil)
        }
            //认证客户端证书
        else if challenge.protectionSpace.authenticationMethod
            == NSURLAuthenticationMethodClientCertificate
        {
            print("客户端证书认证!")
            //获取客户端证书相关信息
            let identityAndTrust:IdentityAndTrust = self.extractIdentity();
            
            let urlCredential:URLCredential = URLCredential(
                identity: identityAndTrust.identityRef,
                certificates: identityAndTrust.certArray as? [AnyObject],
                persistence: URLCredential.Persistence.forSession);
            
            completionHandler(.useCredential, urlCredential);
        }
            
            // 其它情况(不接受认证)
        else {
            print("其它情况(不接受认证)")
            completionHandler(.cancelAuthenticationChallenge, nil);
        }
    }
    //获取客户端证书相关信息
    func extractIdentity() -> IdentityAndTrust {
        var identityAndTrust:IdentityAndTrust!
        var securityError:OSStatus = errSecSuccess
        
        let path: String = Bundle.main.path(forResource: "pub", ofType: "cer")!
        let PKCS12Data = try! Data(contentsOf: URL(fileURLWithPath: path))
        let key : NSString = kSecImportExportPassphrase as NSString
        let options : NSDictionary = [key : "123456"] //客户端证书密码
        //create variable for holding security information
        //var privateKeyRef: SecKeyRef? = nil
        
        var items : CFArray?
        
        securityError = SecPKCS12Import(PKCS12Data as CFData, options, &items)
        
        if securityError == errSecSuccess {
            let certItems:CFArray = items as CFArray!;
            let certItemsArray:Array = certItems as Array
            let dict:AnyObject? = certItemsArray.first;
            if let certEntry:Dictionary = dict as? Dictionary<String, AnyObject> {
                // grab the identity
                let identityPointer:AnyObject? = certEntry["identity"];
                let secIdentityRef:SecIdentity = identityPointer as! SecIdentity!;
                // grab the trust
                let trustPointer:AnyObject? = certEntry["trust"];
                let trustRef:SecTrust = trustPointer as! SecTrust;
                // grab the cert
                let chainPointer:AnyObject? = certEntry["chain"];
                identityAndTrust = IdentityAndTrust(identityRef: secIdentityRef,
                                                    trust: trustRef, certArray:  chainPointer!);
            }
        }
        return identityAndTrust;
    }
}

//定义一个结构体,存储认证相关信息
struct IdentityAndTrust {
    var identityRef:SecIdentity
    var trust:SecTrust
    var certArray:AnyObject
}