首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当应用程序从后台返回前台时,MCSession经常无法重新连接

当应用程序从后台返回前台时,MCSession经常无法重新连接
EN

Stack Overflow用户
提问于 2014-04-06 15:50:52
回答 1查看 557关注 0票数 0

我正在使用多点连接来制作一个聊天应用。起初,一切都运行良好,MCSession可以相互连接。但当用户点击主页按钮,然后点击应用程序图标时,这些应用程序会彼此断开连接,并且通常无法重新连接。但有时它可以重新连接。成功是随机的。

代码语言:javascript
复制
    - (void)viewDidLoad
{
    [super viewDidLoad];
    ...

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(DidBecomeActive:)
                                                 name: UIApplicationDidBecomeActiveNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didEnterBackground:)
                                                 name: UIApplicationDidEnterBackgroundNotification object:nil];

    NSString *displayname=[[NSUUID UUID] UUIDString];
    _MyPeerID=[[MCPeerID alloc] initWithDisplayName:displayname];

}

- (void)DidBecomeActive:(NSNotification *)notification
{

    if (notFirstLaunch==YES) {
        NSLog(@"DidBecomeActive");
        NSString *displayname=[[NSUUID UUID] UUIDString];
        _MyPeerID=[[MCPeerID alloc] initWithDisplayName:displayname];
        [self createSession];
        [self createAdvertiser];
        [self beginBrowsing];


    }
    notFirstLaunch=YES;

}

- (void)didEnterBackground:(NSNotification *)notification
{
    NSLog(@"didEnterBackground");
    [_MySession disconnect];
    _MySession=nil;
    _MyBrowser=nil;
    _MyAdver=nil;


}



- (void)createSession
{
    _MySession=[[MCSession alloc] initWithPeer:_MyPeerID];
    _MySession.delegate=self;
}


- (void)createAdvertiser
{
    _MyAdver=[[MCNearbyServiceAdvertiser alloc] initWithPeer:_MyPeerID discoveryInfo:nil serviceType:MyServiceType];
    _MyAdver.delegate=self;
    [_MyAdver startAdvertisingPeer];
}

- (void)beginBrowsing {
    _MyBrowser=[[MCNearbyServiceBrowser alloc] initWithPeer:_MyPeerID serviceType:MyServiceType];
    _MyBrowser.delegate=self;
    [_MyBrowser startBrowsingForPeers];
}
EN

回答 1

Stack Overflow用户

发布于 2014-05-14 15:07:54

根据您发布的代码判断,没有任何东西重新连接,因为在didEnterBackground中,您断开了会话,并破坏了会话、浏览器和广告商。在DidBecomeActive中,您有一个保护(notFirstLaunch),这意味着会话和广告商只在您第一次激活时创建,而不是在您从后台返回时激活之后创建。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22891335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档