iOS swift常用方法小总结

随着iOS不断发展,swift越来越成熟,也会慢慢取代OC,OC也会慢慢的退出历史舞台

下面这些方法是我总结的一些开发过程中常用方法,希望对大家有用

import UIKit
import SystemConfiguration
import SystemConfiguration.CaptiveNetwork
import CommonCrypto
class NSToolObject: NSObject {
    
    /// 获取本地的json文件
    ///
    /// - Parameter fileName: 文件名称
    /// - Returns: 放回文件内容(字典)
    public static func readJsonFileByFileName(fileName : String) -> Any? {
        let path    = Bundle.main.path(forResource: "\(fileName).json", ofType: nil)
        let data    = NSData(contentsOfFile: path!)
        let jsonStr = try? JSONSerialization.jsonObject(with: data! as Data, options:.allowFragments)
        return jsonStr
    }
    
    /// 获取当前时间
    ///
    /// - Returns: 时间
    public static func currentTime() -> String {
        let dateformatter = DateFormatter()
        dateformatter.dateFormat = "YYYY-MM-dd HH:mm:ss"// 自定义时间格式
        // GMT时间 转字符串,直接是系统当前时间
        return dateformatter.string(from: Date())
    }
    
    /// 获取当前系统时间戳
    ///
    /// - Returns: 时间戳
    public static func currentTimeStamp() -> TimeInterval {
        let date = Date()
        // GMT时间转时间戳 没有时差,直接是系统当前时间戳
        return date.timeIntervalSince1970
    }
    
    /// 将json字符串转成字典
    ///
    /// - Parameter jsonString: json
    /// - Returns: 字典
    public static func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{
        let jsonData:Data = jsonString.data(using: .utf8)!
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
    }
    
    /// 将字典转成json
    ///
    /// - Parameter dictionary: 字典
    /// - Returns: json
    public static func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
    
    /// 判断字符串是否存在
    ///
    /// - Parameter value: 判断的内容
    /// - Returns: 返回true不是字符串,反之是
    public static func stringIsEmpty(value: AnyObject?) -> Bool {
        //首先判断是否为nil
        if (nil == value) {
            //对象是nil,直接认为是空串
            return true
        } else {
            //然后是否可以转化为String
            if let myValue  = value as? String{
                //然后对String做判断
                return myValue == "" || myValue == "(null)" || 0 == myValue.count
            } else {
                //字符串都不是,直接认为是空串
                return false
            }
        }
    }
    
    /// 判断数组是否存在
    ///
    /// - Parameter value: 判断的内容
    /// - Returns: 返回类型
    public static func arrayIsEmpty(value: AnyObject?) -> Bool {
        //首先判断是否为nil
        if ( nil == value ) {
            //对象是nil,直接认为是空数组
            return true;
        } else {
            //然后是否可以转化为String
            if let myValue  = value as? NSArray{
                //然后对String做判断
                return  0 == myValue.count
            } else {
                //字符串都不是,直接认为是空串
                return false
            }
        }
    }
    
    /// 判断字典是否存在
    ///
    /// - Parameter value: 判断的内容
    /// - Returns: 返回类型
    public static func dictionaryIsEmpty(value: AnyObject?) -> Bool {
        //首先判断是否为nil
        if ( nil == value ) {
            //对象是nil,直接认为是空数组
            return true;
        } else {
            //然后是否可以转化为String
            if let myValue  = value as? NSDictionary{
                //然后对String做判断
                return  0 == myValue.count
            } else {
                //字符串都不是,直接认为是空串
                return false
            }
        }
    }
    
    /// 获取当前系统语言
    ///
    /// - Returns: en英文、cn中文
    public static func getCurrentLanguage() -> String {
        let preferredLang = Bundle.main.preferredLocalizations.first! as NSString
        print("当前系统语言:\(preferredLang)")
        switch String(describing: preferredLang) {
        case "en-US", "en-CN":
            return "en"//英文
        case "zh-Hans-US","zh-Hans-CN","zh-Hant-CN","zh-TW","zh-HK","zh-Hans":
            return "cn"//中文
        default:
            return "en"
        }
    }
    
    /// 判断手机型号是否是刘海屏
    ///
    /// - Returns: 返回bool类型,true是刘海平 false是正常屏
    public static func iphoneIsProfiledScreen() ->Bool {
        var systemInfo = utsname()
        uname(&systemInfo)
        let platform = withUnsafePointer(to: &systemInfo.machine.0) { ptr in
            return String(cString: ptr)
        }
        if ( platform == "iPhone10,3" || platform == "iPhone10,6"  || platform == "iPhone11,8" || platform == "iPhone11,2" || platform == "iPhone11,6" || platform == "iPhone11,4") {
            return true
        } else {
            return false
        }
    }
    
    /// 获取手机所连接wifi名称
    ///
    /// - Returns: 返回手机连接wifi名称
    public static func getUsedSSID() -> String {
        let interfaces = CNCopySupportedInterfaces()
        var ssid = ""
        if interfaces != nil {
            let interfacesArray = CFBridgingRetain(interfaces) as! Array<AnyObject>
            if interfacesArray.count > 0 {
                let interfaceName = interfacesArray[0] as! CFString
                let ussafeInterfaceData = CNCopyCurrentNetworkInfo(interfaceName)
                if (ussafeInterfaceData != nil) {
                    let interfaceData = ussafeInterfaceData as! Dictionary<String, Any>
                    ssid = interfaceData["SSID"]! as! String
                }
            }
        }
        return ssid
    }
    
    /// 将字符串md5加密
    ///
    /// - Parameter strs: 要加密的字符串
    /// - Returns: 返回加密后的字符串
    public static func MD5String(strs:String) ->String!{
        let str = strs.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(strs.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.deallocate()
        return String(format: hash as String)
    }
    
    /// 判断手机号是否合法
    ///
    /// - Parameter num: 手机号
    /// - Returns: 返回是否和法,true 为合法、反之
    public static func isTelNumber(num:NSString)->Bool {
        let mobile = "^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$"
        let CM = "^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$"
        let CU = "^1(3[0-2]|5[256]|8[56])\\d{8}$"
        let CT = "^1((33|53|8[09])[0-9]|349)\\d{7}$"
        let regextestmobile = NSPredicate(format: "SELF MATCHES %@",mobile)
        let regextestcm = NSPredicate(format: "SELF MATCHES %@",CM )
        let regextestcu = NSPredicate(format: "SELF MATCHES %@",CU)
        let regextestct = NSPredicate(format: "SELF MATCHES %@",CT)
        if ((regextestmobile.evaluate(with: num) == true) || (regextestcm.evaluate(with: num)  == true) || (regextestct.evaluate(with: num) == true) || (regextestcu.evaluate(with: num) == true))  {
            return true
        } else {
            return false
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王 哪跑!!!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值