多重连接:在Objective-C ++中浏览无声地失败

问题描述 投票:0回答:1

我正在尝试用Objective-C ++编写Multipeer Connectivity应用程序的浏览器/发现端。我想我可以做广告,因为我可以使用Discovery(https://itunes.apple.com/us/app/discovery-dns-sd-browser/id1381004916?mt=12)看到它。但我的浏览器没有看到任何东西。我究竟做错了什么?

#include <iostream>
#include <thread>

#import <MultipeerConnectivity/MultipeerConnectivity.h>

@interface Bowser : NSObject<MCNearbyServiceBrowserDelegate>

- (void)browser:(MCNearbyServiceBrowser *)browser 
    foundPeer:(MCPeerID *)peerID 
    withDiscoveryInfo:(NSDictionary *)info;

- (void)browser:(MCNearbyServiceBrowser *)browser 
    lostPeer:(MCPeerID *)peerID;

@end

@implementation Bowser

- (void)browser:(MCNearbyServiceBrowser *)browser 
    foundPeer:(MCPeerID *)peerID 
    withDiscoveryInfo:(NSDictionary *)info {
    std::cout << "Hello" << std::endl;
}

- (void)browser:(MCNearbyServiceBrowser *)browser 
    lostPeer:(MCPeerID *)peerID {
    std::cout << "Goodbye" << std::endl;
}

@end

int main() {
    MCPeerID* peerid = [[MCPeerID alloc] initWithDisplayName:@"PeerId"];
    Bowser* delegate = [[Bowser alloc] init];

    MCNearbyServiceBrowser* browser = [MCNearbyServiceBrowser alloc];
    [browser initWithPeer:peerid serviceType:@"m"];

    browser.delegate = delegate;

    [browser startBrowsingForPeers];

    using namespace std::chrono_literals;
    std::this_thread::sleep_for(10s);

    [browser stopBrowsingForPeers];
}

关于如何调试正在发生的事情的建议也很有用。任何人......?

macos objective-c++ multipeer-connectivity
1个回答
0
投票

我终于想通了。 MultipeerConnectivity需要一个运行循环。这不在文档中。

我假设MultipeerConnectivity API在方法调用[browser startBrowsingForPeers]时创建了它所需的线程和/或循环。它不是。

此代码中没有任何地方启动了运行循环。另外,有趣的是,直接使用NSThread并不会启动运行循环,即使它是implied that it will

您的应用程序既不创建也不显式管理NSRunLoop对象。每个NSThread对象(包括应用程序的主线程)都会根据需要自动为其创建NSRunLoop对象。如果需要访问当前线程的运行循环,可以使用类方法currentRunLoop。

什么将创建一个运行循环(并启动它)是CFRunLoopRun()

当前线程的运行循环以默认模式运行(请参阅默认运行循环模式),直到使用CFRunLoopStop停止运行循环或从默认运行循环模式中删除所有源和计时器。

那么,阻止它的是CFRunLoopStop(CFRunLoopRef rl)

此函数强制rl停止运行并将控制权返回给调用当前运行循环激活的CFRunLoopRun或CFRunLoopRunInMode的函数。

当然,CFRunLoopStopCFRunLoopRef为参数。你可以通过使用CFRunLoopGetCurrent来获得它,只需记住它是一个参考,并可能随时到期。我认为你可以非常肯定,当你在运行循环中运行的回调时,运行循环不会消失。但我不会指望它后来坚持下去。事实上,在这种情况下,重点是在这一点上杀死它;所以我希望它能消失。

© www.soinside.com 2019 - 2024. All rights reserved.