2013-09-28 42 views
2

我在我的應用程序中使用ios7中的multipeer連接。文件發送和接收工作絕對正常,但是當用戶從我的應用程序訪問控制中心(甚至設置)並關閉藍牙或WiFi時,文件交換將停止工作。當用戶重新開啓他們時,仍然不起作用。爲了讓他們再次工作,用戶必須關閉並重新打開應用程序。Multipeer Connectivity在用戶關閉藍牙時停止工作

的文件,以這種方式發送:

MCSession *session = [[MCSession alloc] 
              initWithPeer:key]; 


        NSCalendar *gregorian = [[NSCalendar alloc] 
              initWithCalendarIdentifier:NSGregorianCalendar]; 

        NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; 
        dateComponents.year = 2100; 
        dateComponents.month = 1; 
        dateComponents.day = 1; 
        dateComponents.hour = 0; 
        dateComponents.minute = 0; 
        dateComponents.second = 0; 

        NSDate *referenceDate = [gregorian dateFromComponents: dateComponents]; 

        NSDate *now = [NSDate date]; 
        NSTimeInterval interval = [now timeIntervalSinceDate:referenceDate]; 

        NSData *Recording = [NSData dataWithContentsOfFile:myFilePath]; 


        NSString* str = [NSString stringWithFormat:@"%@.ext", button.titleLabel.text]; 


        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 
        [dict setObject:str forKey:@"fileName"]; 
        [dict setObject:@"Recording" forKey:@"fileType"]; 
        [dict setObject:Recording forKey:@"FileData"]; 

        NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:dict]; 

        [browser invitePeer:key 
           toSession:session 
          withContext:myData 
           timeout:interval]; 

用戶可以使用重新加載隨時設備:

[browser startBrowsingForPeers]; 

我覺得現在的問題是超時,但我不當然。

+0

您需要在' - (void)applicationDidBecomeActive:(UIApplication *)應用程序委託方法中重新初始化會話。當控制中心被打開然後關閉後,您的應用再次處於活動狀態時會調用該方法。 –

+0

通過重新初始化會話,您的意思只是MCSession,甚至是MCNearbyServiceAdvertiser和MCNearbyServiceBrowser? – Alessandro

+0

如果可以,請重新設置與Multipeer連接框架相關的所有內容。您還需要重新連接所有連接的同級。 –

回答

2

您需要重新初始化- (void)applicationDidBecomeActive:(UIApplication *)application應用程序委託方法中的所有Multipeer Connectivity Framework相關實例。當控制中心被打開然後關閉後,您的應用再次處於活動狀態時會調用該方法。

1

我建議您改爲監視連接狀態的變化,並在檢測到變化時進行拆卸或重新初始化。這是我這個同樣的問題的方法,使用優秀可達套件:

- (void)monitorReachability 
{ 
    // Allocate a reachability object 
    self.reachability = [Reachability reachabilityWithHostname:@"www.google.com"]; 

    [[NSNotificationCenter defaultCenter] addObserverForName:kReachabilityChangedNotification object:nil queue:nil usingBlock:^(NSNotification *note) { 
     Reachability *reachability = note.object; 
     if (reachability.isReachable) { 
      self.isPhysicallyConnected = YES; 
      [self updateNearbyService]; 
     } else { 
      self.isPhysicallyConnected = NO; 
      [self tearDownNearbyService]; 
     } 
    }]; 

    // Start the notifier, which will cause the reachability object to retain itself! 
    [self.reachability startNotifier]; 
} 

teardownupdate你會重建你的Multipeer堆棧。

+0

有趣。但是,如果Google崩潰或互聯網連接中斷,該怎麼辦?然後程序會無故重新啓動會話。 OP正在談論藍牙,而不是WiFi。 (僅供參考,我不是downvoter) –

+1

感謝您的意見。是的,沒有專門檢測藍牙連接狀態的方法(我知道自iOS 7起)。這就是目前對原始問題實際上沒有完美答案的原因,因爲「每當應用程序出現時重新啓動會話」也不是最理想的。 – SG1