AppDelegate.swift 13.4 KB
//
//  AppDelegate.swift
//  ParentAssistant
//
//  Created by 葛建军 on 2018/3/5.
//  Copyright © 2018年 HANGZHOUTEAM. All rights reserved.
//

import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var conn:Reachability!
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        setUpYXIM()
        //1.设置网络状态监听
        NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.networkStatusChange), name: NSNotification.Name.reachabilityChanged, object: nil)
        // 2、获得网络Reachability对象
        // Reachability必须一直存在,所以需要设置为全局变量
        conn = Reachability.forInternetConnection();
        // 3、开启网络状态消息监听
        conn.startNotifier()
        
        AccountManager.shared.setTokenInfo(tokenInfo: AccountManager.shared.loadToken())
        //第一次进来有网且在登录状态要刷新token
        if conn.currentReachabilityStatus().rawValue != NetworkStatus.NotReachable.rawValue &&
            AccountManager.shared.isOnline() {
            AccountManager.shared.refreshUserInfo(AccountManager.shared.phone(), completionHandler: { (finish) in
                if finish {
                    let ID = AccountManager.shared.rawUserInfo!.contentData()["userid"].stringValue
                    YXMessageManager.share.autoLogin(account: ID, token: ID.md5())
                }else{
                    AccountManager.shared.logOut()
                }
            })
        }
        setShareSDKSetting()
        let tabbarVC = Story.instantiateViewControllerWithIdentifier("TabBarController", storyName: "Main") as! TabBarController
        self.window?.rootViewController = tabbarVC
        self.window?.makeKeyAndVisible()
        // 加载广告
        requestAD(vc: tabbarVC)
        return true
    }
    //设置云信的appkey
    func setUpYXIM(){
        var appkey = ""
        var cername = ""
        if Debug.isFormal{
            appkey = "a1ff0bc08fa0d6f95b480d131e55584b"
            cername = "hxyproductpush"
        }else{
            appkey = "330158c080acdf4dc1092d6a74576c2c"
            cername = "parentdevelop"
        }
        let option = NIMSDKOption(appKey: appkey)
        option.apnsCername = cername
        NIMSDK.shared().register(with: option)
        //添加代理
        YXMessageManager.share.addYXDelegate()
    }
    // MARK: - 加载广告页
    func requestAD(vc:TabBarController) -> Void {
        var position:Int = 0
        if Setting.getString("isFirst") == "\(AppDelegate.version())" {//是否是第一次下载
            position = 1
            let adView = ZLaunchAd.create()
            //position 广告位置0-首次广告位1-开屏广告位2-资讯首页3-频道首页4-频道内容5-文章内容页 AccountManager.shared.address
            HTTPServer.shared.getAds(["position":position as AnyObject], completionHandler: { (str, error) in
                httpJsonResule(jsonString: str, error: error, successHandler: { (json) in
                    if json["status"] == 1 && error == nil{
                        if json.contentData().arrayValue.count>0 {
                            let imageResource = ZLaunchAdImageResourceConfigure()
                            imageResource.imageNameOrImageURL = HTTPServer.HOSTImage+json.contentData().arrayValue[0]["fileSrc"].stringValue.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                            imageResource.imageDuration = 5
                            imageResource.imageFrame = UIScreen.main.bounds
                            adView.setImageResource(imageResource, action: {
                                /// 广告点击
                            })
                        }else{
                            NSLog("************\(json.contentData())");
                        }
                    }
                }, failHandler: { (error) in
                })
            })
        }else{
            let view = UIView(frame: CGRect(x: 0, y: 0, width: getScreenWidth(), height: getScreenHeight()))
            view.backgroundColor = UIColor.white
            vc.view.addSubview(view)
            position = 0
            let _ = Setting.save("\(AppDelegate.version())", forKey: "isFirst")
            //position 广告位置0-首次广告位1-开屏广告位2-资讯首页3-频道首页4-频道内容5-文章内容页 AccountManager.shared.address
            HTTPServer.shared.getAds(["position":position as AnyObject], completionHandler: { (str, error) in
                view.removeFromSuperview()
                httpJsonResule(jsonString: str, error: error, successHandler: { (json) in
                    if json["status"] == 1 && error == nil{
                        var images:[String] = []
                        if json.contentData().arrayValue.count>0 {
                            for item in json.contentData().arrayValue {
                                images.append(HTTPServer.HOSTImage+item["fileSrc"].stringValue.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
                            }
                            LaunchIntroductionView.shared(withImages: images, buttonImage: "icon_getin", buttonFrame: CGRect(x: getScreenWidth()/2-551/4, y: getScreenHeight()-150, width: 551/2, height: 45))
                        }
                    }
                }, failHandler: { (error) in
                })
            })
            
        }
    }
    // MARK: - 设置网络
    @objc func networkStatusChange() {
        // 检测手机网络是否可用
        let connection = Reachability.forInternetConnection()
        if connection?.currentReachabilityStatus().rawValue != NetworkStatus.NotReachable.rawValue {
            if AccountManager.shared.isOnline() {
                AccountManager.shared.refreshUserInfo(AccountManager.shared.phone(), completionHandler: { (finish) in
                    if !finish {
                        //从没网变成有网要且在登录状态刷新token,以及如果在我的页面要告知我的页面刷新UI
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "checkNetworkStatusOutOnline"), object: nil)
                    }
                })
            }
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "checkNetworkStatus"), object: nil)
        } else {
            self.window?.makeToast("网络连接不可用")
        }
    }
    // MARK: - 分享设置,统计设置
    func setShareSDKSetting(){
        // 配置友盟SDK产品并并统一初始化
        // [UMConfigure setEncryptEnabled:YES]; // optional: 设置加密传输, 默认NO.
        // [UMConfigure setLogEnabled:YES]; // 开发调试时可在console查看友盟日志显示,发布产品必须移除。
        UMConfigure.initWithAppkey("5a9f50aaf43e4820c50000e3", channel: "App Store")
        UMErrorCatch.initErrorCatch()
        /* appkey: 开发者在友盟后台申请的应用获得(可在统计后台的 “统计分析->设置->应用信息” 页面查看)*/
        
        // 统计组件配置
        MobClick.setScenarioType(eScenarioType.E_UM_NORMAL)
        // [MobClick setScenarioType:E_UM_GAME];  // optional: 游戏场景设置
        
        // Push组件基本功能配置
//        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
//        UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
        //type是对推送的几个参数的选择,可以选择一个或者多个。默认是三个全部打开,即:声音,弹窗,角标等
//        entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionAlert;
//        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
//        [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) {
//        if (granted) {
//        // 用户选择了接收Push消息
//        }else{
//        // 用户拒绝接收Push消息
//        }
//        }];
        
        
        // 请参考「Share详细介绍-初始化第三方平台」
        // 分享组件配置,因为share模块配置可选三方平台较多,代码基本跟原版一样,也可下载demo查看
//        [self configUSharePlatforms];   // required: setting platforms on demand
        
        // ...
        
//        let socialManager = UMSocialManager.default()
//        socialManager!.openLog(false)
//        socialManager!.umSocialAppkey = "58a29d5aaed1797bc80006e2"
//        //设置微信的appKey和appSecret
//        socialManager!.setPlaform(UMSocialPlatformType.wechatSession, appKey: "wxc2ca78fbd4eff355", appSecret: "a2ed68d3ed35c00676fe171193a23acb", redirectURL: "http://mobile.umeng.com/social")
//
//        //设置分享到QQ互联的appKey和appSecret
//        socialManager!.setPlaform(UMSocialPlatformType.QQ, appKey: "1106048082", appSecret: "wy9p3flQnF9aZfjx", redirectURL: "http://mobile.umeng.com/social")
//
//        //设置新浪的appKey和appSecret
//        socialManager!.setPlaform(UMSocialPlatformType.sina, appKey: "3921700954", appSecret: "04b48b094faeb16683c32669824ebdad", redirectURL: "https://sns.whalecloud.com/sina2/callback")
//
//        //设置短信
//        socialManager!.setPlaform(UMSocialPlatformType.sms, appKey: "", appSecret: "", redirectURL: "")
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "ParentAssistant")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                 
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}