utils.swift 20.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
//
//  utils.swift
//  ParentAssistant
//
//  Created by 左丞 on 2018/3/5.
//  Copyright © 2018年 HANGZHOUTEAM. All rights reserved.
//

import UIKit
import QuickLook
import Photos
//MARK: - 服务器和log打印设置
class Debug{
    static let enable=false//是否打印log
    static let isFormal=true//是否是正式服务器
    class func log(_ msg:String){
        if(!Debug.enable){
            return
        }
        NSLog(msg)
    }
}

class Story{
    static func getStory(_ name:String)->UIStoryboard?{
        return UIStoryboard(name: name, bundle: nil);
    }
    static func instantiateViewControllerWithIdentifier(_ sid:String,storyName sname:String)->UIViewController?{
        return Story.getStory(sname)?.instantiateViewController(withIdentifier: sid)
    }
}

func setViewLayer(wight:CGFloat=1,radius:CGFloat=5,color:CGColor=UIColor.lightGray.cgColor,view:UIView){
    setViewBorder(wight: wight, color: color, view: view)
    setViewRadius(radius: radius, view: view)
}

func setViewBorder(wight:CGFloat=1,color:CGColor=UIColor.lightGray.cgColor,view:UIView){
    view.layer.borderColor = color
    view.layer.borderWidth = wight
}

func setViewRadius(radius:CGFloat=5,view:UIView){
    view.layer.cornerRadius = radius
    view.layer.masksToBounds = true
}

func getScreenWidth()->CGFloat{
//    return AppDelegate.instance().window!.frame.size.width
    return UIScreen.main.bounds.size.width
}

func getScreenHeight()->CGFloat{
    return UIScreen.main.bounds.size.height
//    return AppDelegate.instance().window!.frame.size.height
}

//extension AppDelegate{
//    static func instance()->AppDelegate{
//        return UIApplication.shared.delegate as! AppDelegate
//    }
//}

extension UINavigationController {
    func navigationBar(_ navigationBar: UINavigationBar, shouldPopItem item: UINavigationItem) -> Bool{
        if self.viewControllers.count < (navigationBar.items?.count)!{
            return true
        }
        var shouldPop = true
        let vc = self.topViewController
        if vc!.responds(to: #selector(UIViewController.navigationShouldPopOnBackButton)){
            shouldPop = vc!.navigationShouldPopOnBackButton()
        }
        if shouldPop {
            DispatchQueue.main.async(execute: {
                self.popViewController(animated: true)
            })
        }else{
            for oneSubView in navigationBar.subviews {
                if oneSubView.alpha > 0 && oneSubView.alpha < 1{
                    UIView.animate(withDuration: 0.25, animations: {
                        oneSubView.alpha = 1
                    })
                }
            }
        }
        return false
    }
}

extension UIViewController{
    @objc public func navigationShouldPopOnBackButton()->Bool{
        return true
    }
}

class utils: NSObject {

}
//MARK: - 个人信息设置
class Setting{
    class func save(_ value:String?,forKey key:String)->Bool{
        UserDefaults.standard.set(value, forKey: key)
        return UserDefaults.standard.synchronize()
    }
    class func getString(_ key:String)->String?{
        return UserDefaults.standard.string(forKey: key)
    }
    
    class func saveUserInfo(_ info:String?)->Bool{
        if let ret=info{
            UserDefaults.standard.set(ret, forKey: HTTPServer.URL_CURRENT_INFO)
        }else{
            UserDefaults.standard.set(nil, forKey: HTTPServer.URL_CURRENT_INFO)
        }
        return UserDefaults.standard.synchronize()
    }
    class func getUserInfo()->JSON?{
        let ob = UserDefaults.standard.string(forKey: HTTPServer.URL_CURRENT_INFO)
        return JSON.fromString(ob)
        
    }
    
    class func saveDictionary(_ dic:[String:String] ,forKey key:String)->Bool{
        let data=NSKeyedArchiver.archivedData(withRootObject: dic)
        UserDefaults.standard.set(data, forKey: key)
        return UserDefaults.standard.synchronize()
    }
    class func getDictionary(_ key:String)->[String:String]?{
        let data=UserDefaults.standard.data(forKey: key)
        if let d=data{
            return NSKeyedUnarchiver.unarchiveObject(with: d) as? [String:String]
        }
        return nil
    }
    
    class func saveArray(_ arr:[String] ,forKey key:String)->Bool{
        let data=NSKeyedArchiver.archivedData(withRootObject: arr)
        UserDefaults.standard.set(data, forKey: key)
        return UserDefaults.standard.synchronize()
    }
    class func getTheArray(_ key:String)->[String]{
        let data=UserDefaults.standard.data(forKey: key)
        if let d=data{
            return NSKeyedUnarchiver.unarchiveObject(with: d) as! [String]
        }
        return []
    }
    
    
    class func saveJson(_ json:JSON,forKey key:String)->Bool{
        do{
            try UserDefaults.standard.set(json.rawData(), forKey: key)
            return UserDefaults.standard.synchronize()
        }catch{
            return false
        }
    }
    class func getJson(_ key:String)->JSON?{
        let data=UserDefaults.standard.data(forKey: key)
        if let d=data{
            let json = JSON.init(d)
            return json
        }
        return nil
    }
    
    
}
//MARK: - JSON解析
extension JSON{
    func isSuccess()->Bool{
        
        return self[JSONKeyAccount.Status].intValue==1
    }
    func contentData()->JSON{
        return self[JSONKeyAccount.Data]
    }
    
    static func fromString(_ jsonString:String?)->JSON?{
        if let dataFromString = jsonString?.data(using: String.Encoding.utf8, allowLossyConversion: false) {
            let json = JSON.init(dataFromString)
            return json
        }
        return nil
    }
}
final class JSONKeyAccount{
    static let Status="status"
    static let Data="data"
    static let Message="message"
}
//MARK: - MD5字符串加密
extension String{
    func md5() ->String!{
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deinitialize()
        return hash.uppercased
    }
}

public enum DeviceModel : String {
    case Simulator = "Simulator/Sandbox",
    iPod1          = "iPod 1",
    iPod2          = "iPod 2",
    iPod3          = "iPod 3",
    iPod4          = "iPod 4",
    iPod5          = "iPod 5",
    iPad2          = "iPad 2",
    iPad3          = "iPad 3",
    iPad4          = "iPad 4",
    iPhone4        = "iPhone 4",
    iPhone4S       = "iPhone 4S",
    iPhone5        = "iPhone 5",
    iPhone5S       = "iPhone 5S",
    iPhone5C       = "iPhone 5C",
    iPadMini1      = "iPad Mini 1",
    iPadMini2      = "iPad Mini 2",
    iPadMini3      = "iPad Mini 3",
    iPadAir1       = "iPad Air 1",
    iPadAir2       = "iPad Air 2",
    iPhone6        = "iPhone 6",
    iPhone6plus    = "iPhone 6 Plus",
    iPhone6S       = "iPhone 6S",
    iPhone6Splus   = "iPhone 6S Plus",
    iPhone7        = "iPhone 7",
    iPhone7plus    = "iPhone 7 Plus",
    iPhone8        = "iPhone 8 ",
    iPhoneX        = "iPhone X ",
    Unrecognized   = "?unrecognized?"
}

extension UIDevice{
    
    public var deviceModel: DeviceModel{
        var systemInfo = utsname()
        uname(&systemInfo)
        let modelCode = withUnsafeMutablePointer(to: &systemInfo.machine) {
            ptr in String(cString: UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self))
        }
        var modelMap : [ String : DeviceModel ] = [
            "i386"      : .Simulator,
            "x86_64"    : .Simulator,
            "iPod1,1"   : .iPod1,
            "iPod2,1"   : .iPod2,
            "iPod3,1"   : .iPod3,
            "iPod4,1"   : .iPod4,
            "iPod5,1"   : .iPod5,
            "iPad2,1"   : .iPad2,
            "iPad2,2"   : .iPad2,
            "iPad2,3"   : .iPad2,
            "iPad2,4"   : .iPad2,
            "iPad2,5"   : .iPadMini1,
            "iPad2,6"   : .iPadMini1,
            "iPad2,7"   : .iPadMini1,
            "iPhone3,1" : .iPhone4,
            "iPhone3,2" : .iPhone4,
            "iPhone3,3" : .iPhone4,
            "iPhone4,1" : .iPhone4S,
            "iPhone5,1" : .iPhone5,
            "iPhone5,2" : .iPhone5,
            "iPhone5,3" : .iPhone5C,
            "iPhone5,4" : .iPhone5C,
            "iPad3,1"   : .iPad3,
            "iPad3,2"   : .iPad3,
            "iPad3,3"   : .iPad3,
            "iPad3,4"   : .iPad4,
            "iPad3,5"   : .iPad4,
            "iPad3,6"   : .iPad4,
            "iPhone6,1" : .iPhone5S,
            "iPhone6,2" : .iPhone5S,
            "iPad4,1"   : .iPadAir1,
            "iPad4,2"   : .iPadAir2,
            "iPad4,4"   : .iPadMini2,
            "iPad4,5"   : .iPadMini2,
            "iPad4,6"   : .iPadMini2,
            "iPad4,7"   : .iPadMini3,
            "iPad4,8"   : .iPadMini3,
            "iPad4,9"   : .iPadMini3,
            "iPhone7,1" : .iPhone6plus,
            "iPhone7,2" : .iPhone6,
            "iPhone8,1" : .iPhone6S,
            "iPhone8,2" : .iPhone6Splus
        ]
        if let model = modelMap[modelCode] {
            return model
        }
        
        return DeviceModel.Unrecognized
    }
}

extension UIApplication {
    
    class func appVersion() -> String {
        return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
    }
    
    class func appBuild() -> String {
        return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String
    }
    
    class func versionBuild() -> String {
        let version = appVersion(), build = appBuild()
        return version == build ? "v\(version)" : "v\(version)(\(build))"
    }
}
class Theme{
    static func topBarColor()->UIColor{
        return UIColorFromRGB(0xC5DAFF)//UIColorFromRGB(0xff9b34)f6595f
    }
    ///按钮样式
    static func configButton(_ button:UIButton){
        button.backgroundColor=Theme.topBarColor()
        button.layer.cornerRadius=5
        button.layer.shadowOffset = CGSize(width: 2, height: 2);
        button.layer.shadowRadius = 2
        button.layer.shadowOpacity = 0.15
    }
    ///设置圆角阴影
    static func configCard(_ view:UIView){
        view.layer.masksToBounds = false
        view.layer.cornerRadius=4
        view.layer.shadowOffset = CGSize(width: 0, height: 0);
        view.layer.shadowRadius = 1
        view.layer.shadowOpacity = 0.55
    }
    ///地步阴影
    static func configBottomShadow(_ view:UIView){
        view.layer.shadowOffset = CGSize(width: 0,height: 2);
        view.layer.shadowRadius = 1
        view.layer.shadowOpacity = 0.4
    }
    ///设置灰色边框
    static func configBorder(_ view:UIView){
        view.layer.cornerRadius=5
        view.layer.borderColor=UIColor.lightGray.cgColor
        view.layer.borderWidth=1
    }
    static func titleFontSize(){
        
    }
    static func careColor()->UIColor{
        return UIColorFromRGB(0xff6841)
    }
}
func UIColorFromRGB(_ rgbValue: UInt) -> UIColor {
    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}
func UIColorWithRGB(R:CGFloat,G:CGFloat,B:CGFloat)-> UIColor {
    return UIColor.init(red: R/255.0, green: G/255.0, blue: B/255.0, alpha: 1)
}
func getCurrentDate()->String{
    let dateFormat=DateFormatter()
    dateFormat.dateFormat="M月d日"
    return dateFormat.string(from: Date())
}
// MARK: - 获取当前所在周的周一和周日
func getFirstAndLastDayOfThisWeek()->[Date]{
    let calendar = NSCalendar.current
    let dateComponents = calendar.dateComponents([.weekday,.day,.month,.year], from: Date())
    //获取今天是周几
    let weekday = dateComponents.weekday!
    //获取今天是几号
    let day = dateComponents.day!
    
    //计算当前日期和本周的星期一和星期天相差天数
    var firstDiff:Int = 0
    var lastDiff:Int = 0
    if (weekday == 1){
        firstDiff = 1
        lastDiff = 0
    }else{
        firstDiff = calendar.firstWeekday - weekday
        lastDiff = 7 - weekday
    }
    
    var firstComponents = calendar.dateComponents([.weekday,.day,.month,.year], from: Date())
    firstComponents.day = day+firstDiff
    let firstDay = calendar.date(from: firstComponents)
    
    var lastComponents = calendar.dateComponents([.weekday,.day,.month,.year], from: Date())
    lastComponents.day = day+lastDiff
    let lastDay = calendar.date(from: lastComponents)
    return [firstDay!,lastDay!]
}

func getCurrentWeeks()->(weeks:[String],days:[String]){
    let calendar = NSCalendar.current
    let dateComponents = calendar.dateComponents([.weekday,.day,.month,.year], from: Date())
    //获取今天是周几
    let weekday = dateComponents.weekday!
    //计算当前日期和本周的星期一和星期天相差天数
    var firstDiff:Int = 0
    var lastDiff:Int = 0
    if (weekday == 1){
        firstDiff = 1
        lastDiff = 0
    }else{
        firstDiff = calendar.firstWeekday - weekday
        lastDiff = 7 - weekday
    }
    var dateAry:[String] = []
    var weekAry:[String] = []
    for i in firstDiff..<lastDiff+1 {
        let secondsPerDay = i * 24*60*60
        let curDate = Date(timeIntervalSinceNow: TimeInterval(secondsPerDay))
        let dateFormateer = DateFormatter()
        dateFormateer.dateFormat = "d日"
        let dateStr = dateFormateer.string(from: curDate)
        dateAry.append(dateStr)
        dateFormateer.dateFormat = "EEE"
        let weekStr = dateFormateer.string(from: curDate)
        weekAry.append(weekStr)
    }
    return (weekAry,dateAry)
}
func cameraOrPhotPermissions(_ type:Int=0,view:UIView)->Bool{
    if type == 0{
        if !PhotoLibraryPermissions(){
            view.makeToast("请在iPhone的“设置-隐私-照片”选项中,允许慧校园访问你的手机相册。", duration: 2, position: CSToastPositionBottom)
            return false
        }
    }else{
        if !cameraPermissions() {
            view.makeToast("请在iPhone的“设置-隐私-相机”选项中,允许慧校园访问你的相机。", duration: 2, position: CSToastPositionBottom)
            return false
        }
    }
    return true
}

//判断相机权限
func cameraPermissions() -> Bool{
    let authStatus:AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
    if(authStatus == AVAuthorizationStatus.denied || authStatus == AVAuthorizationStatus.restricted) {
        return false
    }else {
        return true
    }
}
//判断相册权限
func PhotoLibraryPermissions() -> Bool {
    let library:PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
    if(library == PHAuthorizationStatus.denied || library == PHAuthorizationStatus.restricted){
        return false
    }else {
        return true
    }
}
///缩放图片
func scaleImage(_ image:UIImage,toSize size:CGSize)->UIImage{
    UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
    image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage!
}
func imageFilePath(_ fileName:String)->String{
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let imagePath=(documentsPath as NSString).appendingPathComponent("cache/image")
    do {
        try Foundation.FileManager.default.createDirectory(atPath: imagePath, withIntermediateDirectories: true, attributes: nil)
    } catch _ {
    }
    return (imagePath as NSString).appendingPathComponent(fileName)
}
func cleanImageCache(){
    //TODO 删除临时图片
    let fm=Foundation.FileManager.default
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let imagePath=(documentsPath as NSString).appendingPathComponent("cache/image")
    if let files=try? fm.contentsOfDirectory(atPath: imagePath){
        for item in files{
            do {
                try fm.removeItem(atPath: (imagePath as NSString).appendingPathComponent(item))
                Debug.log("delete***************")
            } catch _ {
            }
        }
    }
    
    //        NSFileManager *fm = [NSFileManager defaultManager];
    //        NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"];
    //        NSError *error = nil;
    //        for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
    //            BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error];
    //            if (!success || error) {
    //                // it failed.
    //            }
    //        }
}
///时间格式化
func compareWithCurrentDate(_ date:Date)->String{
    let nowDate = Date()
    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "yyyy"
    let nowTime = timeFormatter.string(from: nowDate) as String
    let getTime = timeFormatter.string(from: date) as String
    
    if Int(nowTime)!-Int(getTime)! >= 1{
        timeFormatter.dateFormat="yyyy-MM-dd HH:mm"
    }else{
        timeFormatter.dateFormat = "yyyyMM"
        let nowTime1 = timeFormatter.string(from: nowDate) as String
        let getTime1 = timeFormatter.string(from: date) as String
        if nowTime1==getTime1 {
            timeFormatter.dateFormat = "yyyyMMdd"
            let nowTime2 = timeFormatter.string(from: nowDate) as String
            let getTime2 = timeFormatter.string(from: date) as String
            if Int(nowTime2)!-Int(getTime2)!==0{
                timeFormatter.dateFormat="HH:mm"
            }else if Int(nowTime2)!-Int(getTime2)!==1{
                timeFormatter.dateFormat="'昨天' HH:mm"
            }else if Int(nowTime2)!-Int(getTime2)!==2{
                timeFormatter.dateFormat="'前天' HH:mm"
            }else{
                timeFormatter.dateFormat="MM-dd HH:mm"
            }
        }else{
            timeFormatter.dateFormat="MM-dd HH:mm"
        }
    }
    return timeFormatter.string(from: date)
}
//首页时间格式化
func messageCompareWithCurrentDate(_ date:Date)->String{
    let nowDate = Date()
    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "yyyy"
    let nowTime = timeFormatter.string(from: nowDate) as String
    let getTime = timeFormatter.string(from: date) as String
    
    if Int(nowTime)!-Int(getTime)! >= 1{
        timeFormatter.dateFormat="yyyy-MM-dd-"
    }else{
        timeFormatter.dateFormat = "yyyyMM"
        let nowTime1 = timeFormatter.string(from: nowDate) as String
        let getTime1 = timeFormatter.string(from: date) as String
        if nowTime1==getTime1 {
            timeFormatter.dateFormat = "yyyyMMdd"
            let nowTime2 = timeFormatter.string(from: nowDate) as String
            let getTime2 = timeFormatter.string(from: date) as String
            if Int(nowTime2)!-Int(getTime2)! == 0 {
                timeFormatter.dateFormat="HH:mm"
            }else if Int(nowTime2)!-Int(getTime2)! == 1 {
                timeFormatter.dateFormat="'昨天'"
            }else if Int(nowTime2)!-Int(getTime2)! == 2 {
                timeFormatter.dateFormat="'前天'"
            }else{
                timeFormatter.dateFormat="MM-dd"
            }
        }else{
            timeFormatter.dateFormat="MM-dd"
        }
    }
    return timeFormatter.string(from: date)
}
extension UIViewController{
    ///设置顶栏的各种显示属性
    func configTheme(){
        self.navigationItem.title=self.navigationController?.title
        self.navigationController?.navigationBar.barTintColor=Theme.topBarColor()
        self.navigationController?.navigationBar.tintColor=UIColor.white
        self.navigationController?.navigationBar.isTranslucent=false
        let textAttributes = NSMutableDictionary(capacity:1)
        textAttributes.setObject(UIColor.white, forKey: NSAttributedStringKey.foregroundColor as NSCopying)
        self.navigationController?.navigationBar.titleTextAttributes=textAttributes as! [AnyHashable: Any] as? [NSAttributedStringKey : Any]
    }
    ///套上UINavigationController
    func wrapWithNavigationController()->UINavigationController{
        let nvc=UINavigationController(rootViewController: self)
        configTheme()
        return nvc
        
    }
}

func getPercentEncodingString(str:String) -> String {
    return String(describing: str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
}