ios - 来自实例方法的具有静态 void 的 Objective C Cordova 回调
<p><p>我正在构建一个可以执行 DNS 查询的 Cordova 插件。由于操作是异步的,我需要使用回调来返回值。</p>
<p>我有</p>
<pre><code>#import <dns_sd.h>
....
- (void)dnsQuery:(CDVInvokedUrlCommand*)command
{
id domain = ;
DNSServiceRef serviceRef;
DNSServiceQueryRecord(&serviceRef, 0, 0, "hmspl.de", kDNSServiceType_TXT,
kDNSServiceClass_IN, queryCallback, command);
DNSServiceProcessResult(serviceRef);
DNSServiceRefDeallocate(serviceRef);
}
</code></pre>
<p>然后是回调,也就是一个<code>static void</code>:</p>
<pre><code>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 = ;
for (uint16_t i = 1; i < rdlen; i += 256) {
;
}
NSString *theTXT = [ initWithBytes:txtData.bytes length:txtData.length encoding:NSASCIIStringEncoding];
NSLog(@"%@",
//PROBLEM HERE
;
}
}
@end
</code></pre>
<p>我需要用初始方法返回一个回调:</p>
<pre><code>;
</code></pre>
<p>但我不能在 <code>static void</code> 方法中使用 <code>self</code>。</p>
<p>如何将值 <code>theTXT</code> 返回到 cordova 并将 <code>command.callbackId</code> 从原始方法传递给回调?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p><code>DNSServiceQueryRecord</code>的最后一个参数是应用上下文,而不是传递cordova的命令,而是传递self作为参数</p>
<p>在您的 .h 中</p>
<pre><code>@property (strong, nonatomic) NSString * callbackId;
</code></pre>
<p>在你的 .m 中</p>
<pre><code>- (void)dnsQuery:(CDVInvokedUrlCommand*)command
{
self.callbackId = command.callbackId;
id domain = ;
DNSServiceRef serviceRef;
DNSServiceQueryRecord(&serviceRef, 0, 0, "hmspl.de", kDNSServiceType_TXT,
kDNSServiceClass_IN, queryCallback, (__bridge void*)self);
DNSServiceProcessResult(serviceRef);
DNSServiceRefDeallocate(serviceRef);
}
</code></pre>
<p>所以你现在可以在 queryCallback 中使用它</p>
<pre><code>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 = ;
for (uint16_t i = 1; i < rdlen; i += 256) {
;
}
NSString *theTXT = [ initWithBytes:txtData.bytes length:txtData.length encoding:NSASCIIStringEncoding];
NSLog(@"%@",
;
}
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 来自实例方法的具有静态 void 的 Objective C Cordova 回调,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/27520992/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/27520992/
</a>
</p>
页:
[1]