NSObject+CNLiveExtensions.swift 7.73 KB
//
//  NSObject+CNLiveCurrentVC.swift
//  metaCode
//
//  Created by open on 2023/6/8.
//

import Foundation
import MBProgressHUD
import HandyJSON

//func currentIfChildViewController() -> (UIViewController?){
//    let vc = currentViewController()
//    if vc != nil && vc?.children.count ?? 0 > 0{
//        //有children , 用last
//        return vc?.children.last
//    }else{
//        return vc
//    }
//}

func currentViewController() -> (UIViewController?) {
   var window = UIApplication.shared.keyWindow
   if window?.windowLevel != UIWindow.Level.normal{
     let windows = UIApplication.shared.windows
     for  windowTemp in windows{
       if windowTemp.windowLevel == UIWindow.Level.normal{
          window = windowTemp
          break
        }
      }
    }
    let vc = window?.rootViewController
    let retVC = currentVC(vc)
    return retVC
}

private func currentVC(_ vc :UIViewController?) -> UIViewController? {
   if vc == nil {
      return nil
   }
   if let presentVC = vc?.presentedViewController {
      return currentVC(presentVC)
   }
   else if let tabVC = vc as? UITabBarController {
      if let selectVC = tabVC.selectedViewController {
          return currentVC(selectVC)
       }
       return nil
    }
    else if let naiVC = vc as? UINavigationController {
       return currentVC(naiVC.visibleViewController)
    }
    else {
        return vc
    }
 }

    // 获取当前活动的navigationcontroller
    func navigationViewController() -> UINavigationController{
        var window = UIApplication.shared.keyWindow
        if window?.windowLevel != UIWindow.Level.normal{
          let windows = UIApplication.shared.windows
          for  windowTemp in windows{
            if windowTemp.windowLevel == UIWindow.Level.normal{
               window = windowTemp
               break
             }
           }
         }
        if let isNav = window!.rootViewController?.isKind(of: UINavigationController.self){
            if isNav{
                let nav = window?.rootViewController as! UINavigationController
                return nav
            }else{
                if let isTabbar = window!.rootViewController?.isKind(of: UITabBarController.self){
                    if isTabbar{
                        let tabbar = window?.rootViewController as! UITabBarController
                        let selectVc = tabbar.selectedViewController
                        if let isNavi = selectVc?.isKind(of: UINavigationController.self){
                            if isNavi{
                                let nav = selectVc as! UINavigationController
                                return nav
                            }
                        }
                    }else{
                        
                    }
                }
            }
        }
        return UINavigationController()
    }

/// 弹框提示
/// - Parameter message: 内容提示
func showMessage(message: String) {
    if !message.isNotBlank() {
        return
    }
    
    let delegate = UIApplication.shared.delegate as! AppDelegate
    
    let bgView = UIView.init()
    bgView.backgroundColor = UIColor(white: 0.1, alpha: 0.7)
    bgView.layer.cornerRadius = 8.0
    bgView.clipsToBounds = true
    delegate.window?.addSubview(bgView)
    
    let remindLab = UILabel.init()
    remindLab.textColor = .white
    remindLab.font = Font_15_Fit
    remindLab.textAlignment = .center
    remindLab.numberOfLines = 1
    remindLab.backgroundColor = .clear
    remindLab.text = message
    bgView.addSubview(remindLab)
    
    var width = message.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height:  delegate.window?.bounds.size.height ?? 0), options:.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font:Font_15_Fit], context: nil).size.width
    if width >  (delegate.window?.bounds.size.width ?? 0)/4.0 * 3.0 {
        width =  (delegate.window?.bounds.size.width ?? 0)/4.0 * 3.0
    }
    
    let height = message.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font:Font_15_Fit], context: nil).size.height
    
    bgView.bounds = CGRect(x: 0, y: 0, width: width + 20, height: height + 20)
    bgView.layer.position = CGPoint(x:  (delegate.window?.bounds.size.width ?? 0) / 2.0, y: ( (delegate.window?.bounds.size.height ?? 0) - ConfigManager.shared.keyboardDisplayHeight) / 2.0)
    
    remindLab.bounds = CGRect(x: 0, y: 0, width: width, height: height)
    remindLab.layer.position = CGPoint(x: bgView.bounds.size.width / 2, y: bgView.bounds.size.height / 2)
    
    UIView.animate(withDuration: 1, delay: 1, options: .curveEaseOut) {
        bgView.alpha = 0
    } completion: { finish in
        bgView.removeFromSuperview()
    }
}

/// 展示等待框
/// - Parameter message: 提示词
func showLoading(message: String) {
    let delegate = UIApplication.shared.delegate as! AppDelegate

    delegate.window?.subviews.forEach({ view in
        if view.isKind(of: MBProgressHUD.layerClass) {
            let hub = view as! MBProgressHUD
            hub.removeFromSuperview()
        }
    })
    
    let hub = MBProgressHUD.showAdded(to: delegate.window!, animated: true)
    hub.mode = .indeterminate
    hub.animationType = .fade
    hub.contentColor = .white
    hub.bezelView.color = .black
    hub.bezelView.style = .solidColor
    hub.label.textColor = .white
    if message.isNotBlank() {
        hub.label.text = message
    }
}

/// 隐藏提示词
func hiddenLoading() {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    MBProgressHUD.hide(for: delegate.window!, animated: true)
}

///####模型转换#########
/**
 *  Json转对象
 */
func jsonToModel(_ jsonStr:String,_ modelType:HandyJSON.Type) -> BaseModel {
    if jsonStr == "" || jsonStr.count == 0 {
        #if DEBUG
            print("jsonoModel:字符串为空")
        #endif
        return BaseModel()
    }
    return modelType.deserialize(from: jsonStr)  as! BaseModel
}

/**
 *  Json转数组对象
 */
func jsonArrayToModel(_ jsonArrayStr:String, _ modelType:HandyJSON.Type) ->[BaseModel] {
    if jsonArrayStr == "" || jsonArrayStr.count == 0 {
        #if DEBUG
            print("jsonToModelArray:字符串为空")
        #endif
        return []
    }
    var modelArray:[BaseModel] = []
    let data = jsonArrayStr.data(using: String.Encoding.utf8)
    let peoplesArray = try! JSONSerialization.jsonObject(with:data!, options: JSONSerialization.ReadingOptions()) as? [AnyObject]
    for people in peoplesArray! {
        modelArray.append(newDictionaryToModel(people as! [String : Any], modelType))
    }
    return modelArray

}
/**
 *  ()字典转对象
 */
func newDictionaryToModel(_ dictionStr:[String:Any],_ modelType:HandyJSON.Type) -> BaseModel {
    if dictionStr.count == 0 {
        #if DEBUG
            print("dictionaryToModel:字符串为空")
        #endif
        return BaseModel()
    }
    return modelType.deserialize(from: dictionStr) as! BaseModel
}
/**
 *  字典转对象
 */
func dictionaryToModel(_ dictionStr:[String:Any],_ modelType:HandyJSON.Type,_ path: String) -> BaseModel {
    if dictionStr.count == 0 {
        #if DEBUG
            print("dictionaryToModel:字符串为空")
        #endif
        return BaseModel()
    }
    return modelType.deserialize(from: dictionStr, designatedPath: path) as! BaseModel
}

/**
 *  对象转JSON
 */
func modelToJson(_ model:BaseModel?) -> String {
    if model == nil {
        #if DEBUG
            print("modelToJson:model为空")
        #endif
         return ""
    }
    return (model?.toJSONString())!
}

/**
 *  对象转字典
 */
func modelToDictionary(_ model:BaseModel?) -> [String:Any] {
    if model == nil {
        #if DEBUG
            print("modelToJson:model为空")
        #endif
        return [:]
    }
    return (model?.toJSON())!
}