我是iOS新手,正在学习使用Swift进行编码。我的应用程序需要测量信号强度。我发现这个代码在Objective-C / C上运行,需要一些帮助才能在Swift上实现。这就是我得到的。希望有人可以帮我完成它。
目标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
}
答案 0 :(得分:2)
不要使用dlopen加载CoreTelephony。使用Swift文件顶部的import CoreTelephony
。然后只需使用CTGetSignalStrength,就像它是任何其他函数一样。
答案 1 :(得分:2)
Swift 3解决方案
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
}