iOS Get Signal Strength in Swift (Core Telephony)

断了今生、忘了曾经 提交于 2020-01-14 19:53:28

问题


I'm new to iOS, and am learning to code with Swift. My app needs to measure the signal strength. I've found this code working on Objective-C/C, and need some help to implement on Swift. Here is what I got. Hope someone can help me finish it.

OBJECTIVE C

    int getSignalStrength()
    {
       void *libHandle = dlopen("/System/Library/Frameworks/CoreTelephony.framework/CoreTelephony", RTLD_LAZY);
       int (*CTGetSignalStrength)();
       CTGetSignalStrength = dlsym(libHandle, "CTGetSignalStrength");
       if( CTGetSignalStrength == NULL) NSLog(@"Could not find CTGetSignalStrength");
       int result = CTGetSignalStrength();
       dlclose(libHandle);
       return result;
    }

SWIFT

    func getSignalStrength()->Int{
       var result : Int! = 0
       let libHandle = dlopen ("/System/Library/Frameworks/CoreTelephony.framework/CoreTelephony", RTD_LAZY)
       ** help **
       var CTGetSignalStrength = dlsym(libHandle, "CTGetSignalStrength")
       if (CTGetSignalStrength != nil){
           result = CTGetSignalStrength()
       }
       dlclose(libHandle)
       return result
    }

回答1:


Don't use dlopen to load CoreTelephony. Use import CoreTelephony at the top of your Swift file. Then just use CTGetSignalStrength as if it were any other function.




回答2:


Swift 3 Solution

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
 }


来源:https://stackoverflow.com/questions/25429732/ios-get-signal-strength-in-swift-core-telephony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!