来自实例方法的具有静态 void 的 Objective C Cordova 回调
Posted
技术标签:
【中文标题】来自实例方法的具有静态 void 的 Objective C Cordova 回调【英文标题】:Objective C Cordova callbacks with static void from instance method 【发布时间】:2014-12-17 08:13:46 【问题描述】:我正在构建一个可以执行 DNS 查询的 Cordova 插件。由于操作是异步的,我需要使用回调来返回值。
我有
#import <dns_sd.h>
....
- (void)dnsQuery:(CDVInvokedUrlCommand*)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
从原始方法传递给回调?
【问题讨论】:
【参考方案1】:DNSServiceQueryRecord
的最后一个参数是应用程序上下文,而不是传递cordova 的命令,而是将self 作为参数传递
在您的 .h 中
@property (strong, nonatomic) NSString * callbackId;
在你的 .m 中
- (void)dnsQuery:(CDVInvokedUrlCommand*)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];
【讨论】:
以上是关于来自实例方法的具有静态 void 的 Objective C Cordova 回调的主要内容,如果未能解决你的问题,请参考以下文章