2013-08-13 2 views
-1

안녕하세요, 백그라운드에서 FireBase를 실행하려고합니다.백그라운드에서 FireBase를 실행 중입니다.

코드가 다음과 같습니다. 코드가 다음을 수행합니다. - 앱이 백그라운드로 전환되면 Firebase에 새로운 채팅 메시지가 있는지 계속 확인합니다. 그런 다음 새 채팅 메시지가 발견되면 응용 프로그램 배지 번호를 증가시킵니다. 어떤 이유로

- (void) fetch 
{ 
    if([[API sharedInstance] isAuthorized]) 
    { 

     NSLog(@"in background fetching"); 

     Firebase * ref = nil; 

     NSDictionary * investor = [[API sharedInstance] investor]; 
     NSDictionary * startup = [[API sharedInstance] startup]; 

     if(investor != nil) { 

      NSInteger iid = [[API sharedInstance] userid]; 
      NSString * path = [NSString stringWithFormat: @"http://example.firebaseIO.com/investor/%d/conversations", iid]; 

      ref = [[Firebase alloc] initWithUrl:path]; 
     } 
     else if(startup != nil) 
     { 
      NSInteger sid = [[startup objectForKey: @"id"] intValue]; 
      NSString * path = [NSString stringWithFormat: @"http://example.firebaseIO.com/startup/%d/conversations", sid]; 
      ref = [[Firebase alloc] initWithUrl:path]; 
     } 


     if(ref) 
     { 

      NSString * path = [NSString stringWithFormat: @"http://kickcircle.firebaseIO.com/conversations"]; 
      Firebase * conv = [[Firebase alloc] initWithUrl: path]; 

      [ref observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) { 

       // name of conversation 
       NSString * name = snapshot.name; 
       Firebase * ref1 = [conv childByAppendingPath: name]; 

       [ref1 observeSingleEventOfType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) { 


        if(snapshot.value != [NSNull null] && ![snapshot.value isKindOfClass: [NSString class]]) 
        { 


         NSLog(@"in background fetching7"); 

         FDataSnapshot * chatsnapshot = [snapshot childSnapshotForPath: @"chats"]; 

         NSInteger numChatMessages = chatsnapshot.childrenCount; 
         numberOfTotalChatMessages += numChatMessages; 

         NSMutableDictionary *m = [snapshot.value mutableCopy]; 
         [m setValue: snapshot.name forKey: @"ref_name"]; 

         // number of messages read for that conversation 
         NSInteger current_user = [[API sharedInstance] userid]; 
         NSString * userpath = [NSString stringWithFormat: @"users/%d", current_user]; 
         FDataSnapshot * usersnapshot = [snapshot childSnapshotForPath: userpath]; 

         if(usersnapshot.value != [NSNull null] && ![usersnapshot.value isKindOfClass: [NSString class]]) 
         { 
          NSDictionary * userdict = usersnapshot.value; 
          NSInteger numUserMessagesRead = [userdict[@"numOfMessages"] intValue]; 

          if(numChatMessages > numUserMessagesRead) 
          { 
           if([[m objectForKey: @"last_from_id"] intValue] != [[API sharedInstance] userid]) 
           { 
            [m setValue: @"true" forKey: @"bubble"]; 

            newChats = YES; 

            if(inBackGround) 
            { 
             [self addNotification]; 
            } 
           } 
           else{ 
            numUserMessagesRead = numChatMessages; 
           } 
          } 
          else { 
           numUserMessagesRead = numChatMessages; 
          } 

          numberOfMessagesRead += numUserMessagesRead; 

          [m setValue: [NSNumber numberWithInt: numUserMessagesRead] forKey: @"numMessagesRead"]; 
         } 
         else { 

          if([[m objectForKey: @"last_from_id"] intValue] != [[API sharedInstance] userid]) 
          { 
           [m setValue: @"true" forKey: @"bubble"]; 

           newChats = YES; 

           [m setValue: [NSNumber numberWithInt: 0] forKey: @"numMessagesRead"]; 


           if(inBackGround) 
           { 
            [self addNotification]; 
           } 
          } 
          else { 
           numberOfMessagesRead += numChatMessages; 

           [m setValue: [NSNumber numberWithInt: numChatMessages] forKey: @"numMessagesRead"]; 
          } 
         } 

         [m setValue: [NSNumber numberWithInt: numChatMessages] forKey: @"numChatMessages"]; 

         [self.chats addObject: m]; 

         [self calculateChatNumber]; 

         NSNumber * index = [NSNumber numberWithInt: self.chats.count - 1]; 
         [read setValue: index forKey: snapshot.name]; 

         PLRightMenuViewController * rightPanel = (PLRightMenuViewController *) self.viewController.rightPanel; 
         [rightPanel.tableView reloadData]; 


        } 

       }]; 

      }]; 


      [ref observeEventType:FEventTypeChildChanged withBlock:^(FDataSnapshot *snapshot) { 

       NSString * name = snapshot.name; 
       Firebase * ref1 = [conv childByAppendingPath: name]; 

       [ref1 observeSingleEventOfType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) 
       { 

        if(snapshot.value != [NSNull null] && ![snapshot.value isKindOfClass: [NSString class]]) 
        { 

         NSLog(@"in background fetching8"); 

         NSMutableDictionary *m = [snapshot.value mutableCopy]; 
         [m setValue: snapshot.name forKey: @"ref_name"]; 

         numberOfTotalChatMessages += 1; 


         if([read objectForKey: snapshot.name]) 
         { 
          NSInteger index = [[read objectForKey: snapshot.name] intValue]; 

          // number of current chats for conversation 
          NSInteger numChats = [[[self.chats objectAtIndex: index] objectForKey: @"numChatMessages"] intValue]; 

          // number of messages read 
          NSNumber * readMessages = [[self.chats objectAtIndex: index] objectForKey: @"numMessagesRead"]; 
          NSInteger readMessagesInt = [readMessages intValue]; 

          NSInteger current_user = [[API sharedInstance] userid]; 
          NSString * userpath = [NSString stringWithFormat: @"users/%d", current_user]; 
          FDataSnapshot * usersnapshot = [snapshot childSnapshotForPath: userpath]; 

          if(usersnapshot.value != [NSNull null] && ![usersnapshot.value isKindOfClass: [NSString class]]) 
          { 
           NSDictionary * userdict = usersnapshot.value; 
           NSInteger numUserMessagesRead = [userdict[@"numOfMessages"] intValue]; 

           if([[m objectForKey: @"last_from_id"] intValue] != [[API sharedInstance] userid]) { 

            newChats = YES; 

            [m setValue: @"true" forKey: @"bubble"]; 

            if(numUserMessagesRead > readMessagesInt) { 

             numberOfMessagesRead += numUserMessagesRead - readMessagesInt; 

             readMessagesInt = numUserMessagesRead; 


             if(inBackGround) 
             { 
              [self addNotification]; 
             } 
            } 
           } 
           else { 
            numberOfMessagesRead += numChats + 1 - readMessagesInt; 
            readMessagesInt = numChats + 1; 
           } 

          } 
          else { 

           if([[m objectForKey: @"last_from_id"] intValue] != [[API sharedInstance] userid]) 
           { 
            [m setValue: @"true" forKey: @"bubble"]; 
            newChats = YES; 


            if(inBackGround) 
            { 
             [self addNotification]; 
            } 
           } 
           else { 
            numberOfMessagesRead += numChats + 1 - readMessagesInt; 
            readMessagesInt = numChats + 1; 
           } 
          } 

          [self.chats removeObjectAtIndex: index]; 

          [m setValue: [NSNumber numberWithInt: numChats + 1] forKey: @"numChatMessages"]; 
          [m setValue: [NSNumber numberWithInt: readMessagesInt] forKey: @"numMessagesRead"]; 


          [self.chats addObject: m]; 

          NSNumber * index1 = [NSNumber numberWithInt: self.chats.count - 1]; 
          [read setValue: index1 forKey: snapshot.name]; 
         } 

         [self calculateChatNumber]; 

         PLRightMenuViewController * rightPanel = (PLRightMenuViewController *) self.viewController.rightPanel; 
         [rightPanel.tableView reloadData]; 
        } 


       }]; 

      }]; 
     } 
    } 
} 

이 앱이 백그라운드로 갈 때 (새 메시지가있는 경우 배지가 증가되지 않음) 작동하지 않습니다 :

- (void)applicationDidEnterBackground:(UIApplication *)application 
{ 

    [self.locationManager startMonitoringSignificantLocationChanges]; 

    NSLog(@"in background fetching8"); 

    if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4 
     if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking 
      UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance 


      __block UIBackgroundTaskIdentifier background_task; //Create a task object 
      background_task = [application beginBackgroundTaskWithExpirationHandler:^{ 
       [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks 
       background_task = UIBackgroundTaskInvalid; //Set the task to be invalid 
       //System will be shutting down the app at any point in time now 
      }]; 


      //Background tasks require you to use asyncrous tasks 
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
       //Perform your tasks that your application requires 


       NSLog(@"in background fetching98"); 

       inBackGround = YES; 

       [self fetch]; 


       [application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform 
       background_task = UIBackgroundTaskInvalid; //Invalidate the background_task 
      }); 
     } 
    } 


    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 
} 

을 가져옵니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

답변

2

백그라운드에서 실행하려고 시도하는 방법은 백그라운드 작업 완료를 위해 예약되어 있습니다. 실제로는 코드의 작동 가능한 실행을위한 것이 아닙니다. 푸시 알림 모델로 이동하거나 iOS 7 통합 업데이트를 기다려야합니다.

beginBackgroundTaskWithExpirationHandler : 앱이 백그라운드 상태로 전환 되었더라도 앱이 일시 중지되기 전에 완료해야하는 iOS 신호를 보냅니다. endBackgroundTask : 앱의 작업이 완료된 iOS에 신호를 보내 앱이 필요할 때 일시 중지 상태로 이동할 수있게합니다. 앱이 전경에서 포 그라운드에 있으면이 통화는 아무 효과가 없으므로 사용하지 않아도됩니다.

백그라운드 작업은 무료로 적용되지 않으며 완료하는 데 많은 시간이 소요되지 않습니다. beginBackgroundTaskWithExpirationHandler : "만료 처리기"부분은 작업 출력이 평생 지속되는 경우 정리 코드를 지정하는 블록입니다. 백그라운드 작업으로 실행되는 코드는 UI 업데이트 또는 openGL 호출을하지 않아야합니다 (앱이 오프 스크린이므로).

나는 최대 10 분이내라고 생각합니다.

관련 문제