2015-01-07 3 views
0

Я делаю приватный чат с Parse и каркасом MessageViewController. Мне удалось отобразить разговор всех сообщений от пользователя А до пользователя Б, но я не могу отличить, кто является отправителем или получателем с пузырем. В сеансе parse У меня есть класс «Чат» со столбцами: «objectId», «DestinateurId» (получатель), «senderId» (отправитель), «текст», «createdAt». Когда я отправляю сообщение, это хорошо дополняет базу данных. Я просто хочу, чтобы, когда пользователь A отправляет сообщение пользователю B, мы видим, что пользователь A использует BubbleMessageStyleOutgoing и пользователь B получит BubbleMessageStyleIncoming. (В настоящий момент каждое сообщение находится в BubbleMessageStyleOutgoing)Частный чат с Parse and MessagesViewController

Итак, во-первых, я делаю запрос на получение сообщений от отправителя и получателя. С этим я получаю все сообщения, которые мне нужно отображать. вопрос: я не могу получить доступ к сообщениям NSArray * из viewDidLoad, так как я могу отличить это сообщение от отправителя или получателя? (Потому что мне нужно дифференцировать в другой метод (- (BubbleMessageStyle) messageStyleForRowAtIndexPath: (NSIndexPath *) indexPath)

Вот мой код:

ChatViewController.h:

#import "MessagesViewController.h" 

@interface ChatViewController : MessagesViewController 
@property (strong, nonatomic) NSMutableArray *messages; 
@property (strong, nonatomic) NSString *destinateurChat; 
@property (strong, nonatomic) NSArray *senderMsg; 
@property (strong, nonatomic) NSArray *destinateurMsg; 
@property (strong, nonatomic) NSArray *msg; 
@end 

ChatViewController.m:

#import "ChatViewController.h" 
#import <Parse/Parse.h> 
#import "SVProgressHUD.h" 
#import "MBProgressHUD.h" 

@interface ChatViewController() 

@end 
id message; 
NSDate *receiveDate; 
NSString *text; 
@implementation ChatViewController 

#pragma mark - View lifecycle 
- (void)viewDidLoad 
{ 

    [super viewDidLoad]; 
    self.title = @"Messages"; 
    PFQuery *query1 = [PFQuery queryWithClassName:@"Chat"]; 
    [query1 whereKey:@"DestinateurId" equalTo:self.destinateurChat]; 
    [query1 whereKey:@"senderId" equalTo:[[PFUser currentUser] objectId]]; 
    //[query1 orderByDescending:@"createdAt"]; 
    PFQuery *query2 = [PFQuery queryWithClassName:@"Chat"]; 
    [query2 whereKey:@"DestinateurId" equalTo:[[PFUser currentUser] objectId]]; 
    [query2 whereKey:@"senderId" equalTo:self.destinateurChat]; 
    //[query2 orderByDescending:@"createdAt"]; 
    [MBProgressHUD showHUDAddedTo:self.view animated:YES]; 
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC); 
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 
     PFQuery *orQuery = [PFQuery orQueryWithSubqueries:@[query1, query2]]; 
     [orQuery orderByDescending:@"createdAt"]; 
     [orQuery findObjectsInBackgroundWithBlock:^(NSArray *messages, NSError *error) { 
      // Do real error handling in your app... 
self.msg = messages; 
      for (PFObject *message in messages) { 
       if ([message[@"senderId"] isEqualToString:[[PFUser currentUser] objectId]]) { 
        // This is an outgoing message 
        self.senderMsg = [messages valueForKey:@"text"]; 
        self.messages = [[NSMutableArray alloc] init]; 
        [self.messages addObjectsFromArray:self.senderMsg]; 
        [self.tableView reloadData]; 
       } else { 
        // This is an incoming message 
        self.destinateurMsg = [messages valueForKey:@"text"]; 
        [self.messages addObjectsFromArray:self.destinateurMsg]; 
        [self.tableView reloadData]; 
       } 
      } 
     }]; 
     [MBProgressHUD hideHUDForView:self.view animated:YES]; 
    }); 


    NSLog(@"%@", self.senderMsg); 
NSLog(@"%@", self.msg); 
    UIButton *exitButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [exitButton addTarget:self action:@selector(backToInboxView) forControlEvents:UIControlEventTouchUpInside]; 
    [exitButton setTitle:@"Inbox" forState:UIControlStateNormal]; 
    exitButton.frame = CGRectMake(0.0, 0.0, 60, 60); 
    [self.view addSubview:exitButton]; 
    } 

#pragma mark - Table view data source 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return self.messages.count; 
} 

#pragma mark - Messages view controller 
- (BubbleMessageStyle)messageStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return self.destinateurMsg ? BubbleMessageStyleIncoming : BubbleMessageStyleOutgoing; 
} 


- (NSString *)textForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return [self.messages objectAtIndex:indexPath.row]; 
} 

- (void)sendPressed:(UIButton *)sender withText:text 
{ 
    [self.messages addObject:text]; 
    if((self.messages.count - 1) % 2) 
     [MessageSoundEffect playMessageSentSound]; 
    else 
     [MessageSoundEffect playMessageReceivedSound]; 
    [self finishSend]; 
    PFObject *chat = [PFObject objectWithClassName:@"Chat"]; 
    [chat setObject:self.destinateurChat forKey:@"DestinateurId"]; 
    [chat setObject:text forKey:@"text"]; 
    [chat setObject:[[PFUser currentUser] objectId] forKey:@"senderId"]; 

    [chat saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) { 
     if (error) { 
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"An error occurred!" 
                   message:@"Please try sending your message again." 
                   delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
      [SVProgressHUD dismiss]; 
      [alertView show]; 
     } 
     else { 
      // Everything was successful! 
      [SVProgressHUD dismiss]; 
     } 
    }]; 
} 

- (void)backToInboxView{ 
    [self.navigationController popToRootViewControllerAnimated:YES]; 
} 

@end 

Я буду очень рад следовать вашим советам.

ответ

0

Я бы попытался выполнить запрос «или».

Вот PARSE пример кода по этой теме:

PFQuery *lotsOfWins = [PFQuery queryWithClassName:@"Player"]; 
[lotsOfWins whereKey:@"wins" greaterThan:@150]; 

PFQuery *fewWins = [PFQuery queryWithClassName:@"Player"]; 
[fewWins whereKey:@"wins" lessThan:@5]; 
PFQuery *query = [PFQuery orQueryWithSubqueries:@[fewWins,lotsOfWins]]; 
[query findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) { 
    // results contains players with lots of wins or only a few wins. 
}]; 

Для вас, это, казалось бы выглядеть следующим образом:

PFQuery *query1 = [PFQuery queryWithClassName:@"Chat"]; 
[query1 whereKey:@"DestinateurId" equalTo:self.destinateurChat]; 
[query1 whereKey:@"senderId" equalTo:[[PFUser currentUser] objectId]]; 

PFQuery *query2 = [PFQuery queryWithClassName:@"Chat"]; 
[query2 whereKey:@"DestinateurId" equalTo:[[PFUser currentUser] objectId]]; 
[query2 whereKey:@"senderId" equalTo:self.destinateurChat]; 

PFQuery *orQuery = [PFQuery orQueryWithSubqueries:@[query1, query2]]; 
[orQuery findObjectsInBackgroundWithBlock:^(NSArray *messages, NSError *error) { 
    // Do real error handling in your app... 
    for (PFObject *message in messages) { 
     if ([message[@"senderId"] isEqualToString:[[PFUser currentUser] objectId]]) { 
      // This is an outgoing message 

     } else { 
      // This is an incoming message 

     } 
    } 
}]; 
+0

Хорошо, я рад узнать, что! Итак, теперь я могу знать, является ли это входящим или исходящим сообщением, но как получить доступ к этой информации из viewDidLoad? Поскольку конечная цель заключается в том, чтобы реализовать это в методе «(BubbleMessageStyle) messageStyleForRowAtIndexPath: (NSIndexPath *) indexPath» – Viny76

+0

@ Viny76 Я обычно настраивал путь метода загрузки данных и показывал диалог «Подождите ...» во время выполнения запроса , тогда, когда данные поступают, я назначаю данные локальному свойству и вызываю 'reloadData' в свой' UITableView'. Проверьте «MBProgressHUD» (бесплатно на github), чтобы показать диалог «Подождите ...». – mbm29414

+0

Я обновил свой код, это нормально, я reloadData, но когда вы говорите: «Я назначаю данные локальному свойству», можете ли вы использовать это свойство из viewDidLoad? Я должен использовать его в messageStyleForRowAtIndexPath. Извините, если я этого не понимаю. (PS: спасибо за вашу помощь!), И я знаю MBProgreesHUD :) – Viny76

Смежные вопросы