iOS开发Swift

Swift – 使用CoreTelephony获取运营商信息、网络制式(4G、3G、2G)

在项目开发中,有时需要获取当前设备的运营商信息(是电信、还是联通、移动)。又或者想知道当前设备使用的移动网络制式(4G3G、还是 2G)。这个借助系统的 CoreTelephony 框架就能够实现。

1,效果图

程序启动后自动获取手机的运营商、网络制式等信息,并输出到控制台中。

2,样例代码
import UIKit
import CoreTelephony
 
class ViewController: UIViewController {
     
    override func viewDidLoad() {
        super.viewDidLoad()
         
        //获取并输出运营商信息
        let info = CTTelephonyNetworkInfo()
        if let carrier = info.subscriberCellularProvider {
            let currentRadioTech = info.currentRadioAccessTechnology!
            print("数据业务信息:\(currentRadioTech)")
            print("网络制式:\(getNetworkType(currentRadioTech: currentRadioTech))")
            print("运营商名字:\(carrier.carrierName!)")
            print("移动国家码(MCC):\(carrier.mobileCountryCode!)")
            print("移动网络码(MNC):\(carrier.mobileNetworkCode!)")
            print("ISO国家代码:\(carrier.isoCountryCode!)")
            print("是否允许VoIP:\(carrier.allowsVOIP)")
        }
    }
     
    //根据数据业务信息获取对应的网络类型
    func getNetworkType(currentRadioTech:String) -> String {
        var networkType = ""
        switch currentRadioTech {
        case CTRadioAccessTechnologyGPRS:
            networkType = "2G"
        case CTRadioAccessTechnologyEdge:
            networkType = "2G"
        case CTRadioAccessTechnologyeHRPD:
            networkType = "3G"
        case CTRadioAccessTechnologyHSDPA:
            networkType = "3G"
        case CTRadioAccessTechnologyCDMA1x:
            networkType = "2G"
        case CTRadioAccessTechnologyLTE:
            networkType = "4G"
        case CTRadioAccessTechnologyCDMAEVDORev0:
            networkType = "3G"
        case CTRadioAccessTechnologyCDMAEVDORevA:
            networkType = "3G"
        case CTRadioAccessTechnologyCDMAEVDORevB:
            networkType = "3G"
        case CTRadioAccessTechnologyHSUPA:
            networkType = "3G"
        default:
            break
        }
        return networkType
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
3.如何获取蜂窝信号强度呢?

可以用下面的代码,但是从ios11开始已经不支持了。

import CoreTelephony
import Darwin

    static func getSignalStrength()->Int{
        var result : Int = 0
        //int CTGetSignalStrength();
        let libHandle = dlopen ("/System/Library/Frameworks/CoreTelephony.framework/CoreTelephony", RTLD_NOW)
        let CTGetSignalStrength2 = dlsym(libHandle, "CTGetSignalStrength")

        typealias CFunction = @convention(c) () -> Int

        if (CTGetSignalStrength2 != nil) {
            let fun = unsafeBitCast(CTGetSignalStrength2!, to: CFunction.self)
            let result = fun()
            return result;
            print("!!!!result \(result)")
        } 
     return -1
 }