我正在构建一个可以执行 DNS 查询的 Cordova 插件。由于操作是异步的,我需要使用回调来返回值。
我有
#import <dns_sd.h>
....
- (void)dnsQueryCDVInvokedUrlCommand*)command
{
id domain = [command.arguments objectAtIndex:0];
DNSServiceRef serviceRef;
DNSServiceQueryRecord(&serviceRef, 0, 0, "hmspl.de", kDNSServiceType_TXT,
kDNSServiceClass_IN, queryCallback, command);
DNSServiceProcessResult(serviceRef);
DNSServiceRefDeallocate(serviceRef);
}
然后是回调,也就是一个static void :
static void queryCallback(DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex,
DNSServiceErrorType errorCode, const char *fullname, uint16_t rrtype,
uint16_t rrclass, uint16_t rdlen, const void *rdata, uint32_t ttl, void *context) {
if (errorCode == kDNSServiceErr_NoError && rdlen > 1) {
NSMutableData *txtData = [NSMutableData dataWithCapacity:rdlen];
for (uint16_t i = 1; i < rdlen; i += 256) {
[txtData appendBytes:rdata + i length:MIN(rdlen - i, 255)];
}
NSString *theTXT = [[NSString alloc] initWithBytes:txtData.bytes length:txtData.length encoding:NSASCIIStringEncoding];
NSLog(@"%@",
//PROBLEM HERE
[self.commandDelegate sendPluginResult:theTXT callbackId:context.callbackId];
}
}
@end
我需要用初始方法返回一个回调:
[self.commandDelegate sendPluginResult:theTXT callbackId:command.callbackId];
但我不能在 static void 方法中使用 self 。
如何将值 theTXT 返回到 cordova 并将 command.callbackId 从原始方法传递给回调?
Best Answer-推荐答案 strong>
DNSServiceQueryRecord 的最后一个参数是应用上下文,而不是传递cordova的命令,而是传递self作为参数
在您的 .h 中
@property (strong, nonatomic) NSString * callbackId;
在你的 .m 中
- (void)dnsQueryCDVInvokedUrlCommand*)command
{
self.callbackId = command.callbackId;
id domain = [command.arguments objectAtIndex:0];
DNSServiceRef serviceRef;
DNSServiceQueryRecord(&serviceRef, 0, 0, "hmspl.de", kDNSServiceType_TXT,
kDNSServiceClass_IN, queryCallback, (__bridge void*)self);
DNSServiceProcessResult(serviceRef);
DNSServiceRefDeallocate(serviceRef);
}
所以你现在可以在 queryCallback 中使用它
static void queryCallback(DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex,
DNSServiceErrorType errorCode, const char *fullname, uint16_t rrtype,
uint16_t rrclass, uint16_t rdlen, const void *rdata, uint32_t ttl, void *context) {
if (errorCode == kDNSServiceErr_NoError && rdlen > 1) {
NSMutableData *txtData = [NSMutableData dataWithCapacity:rdlen];
for (uint16_t i = 1; i < rdlen; i += 256) {
[txtData appendBytes:rdata + i length:MIN(rdlen - i, 255)];
}
NSString *theTXT = [[NSString alloc] initWithBytes:txtData.bytes length:txtData.length encoding:NSASCIIStringEncoding];
NSLog(@"%@",
[context.commandDelegate sendPluginResult:theTXT callbackId:context.callbackId];
}
}
关于ios - 来自实例方法的具有静态 void 的 Objective C Cordova 回调,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/27520992/
|