IOS Get Signal Strength in Swift (Core Telephony)

I am new to iOS and am learning code with Swift. My application should measure the signal strength. I found this code running on Objective-C / C and you need help implementing it in Swift. Here is what I got. Hope someone can help me finish it.

GOAL 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 } 
+3
source share
2 answers

Do not use dlopen to download CoreTelephony. Use import CoreTelephony at the top of your Swift file. Then just use CTGetSignalStrength, as if it were any other function.

+2
source

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 } 
+2
source

Source: https://habr.com/ru/post/1213391/


All Articles