iOS - 将新数据发布到NSMutableArray时触发通知?

时间:2016-07-05 23:56:34

标签: ios mysql objective-c push-notification

我在我的服务器上设置推送通知,一切都很好。 例如我可以随时向所有用户发送通知(因为所有设备令牌都存储在我的数据库中)。也就是说,当应用程序中镜像的服务器上的数据更新时,我想向设备发送推送通知( 例如 ,当新消息发布到服务器)?

更具体地说: 请参阅下面的代码,用于在tableview中显示所有收到的消息。我如何进行此操作,以便登录用户在更新self.messages时收到通知?

ViewController.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *PointsTableIdentifier = @"MyMessagesCell";

    MyMessagesCell *cell = (MyMessagesCell *)[tableView dequeueReusableCellWithIdentifier:PointsTableIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyMessagesCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];

    }


    NSDictionary *receivedSubjectLine = [self.messages objectAtIndex:indexPath.row];

    NSString *messageSubject = [receivedSubjectLine objectForKey:@"node_title"];


    [cell.subjectLine setText:messageSubject];



    NSDictionary *fromUser = [self.messages objectAtIndex:indexPath.row];

    NSString *userName = [fromUser objectForKey:@"name"];

    [cell.senderName setText:userName];



    NSDictionary *receivedBody = [self.messages objectAtIndex:indexPath.row];

    NSString *messageBody = [receivedBody objectForKey:@"body"];

    [cell.fullMessage setText:messageBody];


    NSDictionary *receivedTime = [self.messages objectAtIndex:indexPath.row];

    NSString *timeStamp = [receivedTime objectForKey:@"swaptime"];

        NSLog(@"The timestamp is %@", timeStamp);

    [cell.swapTime setText:timeStamp];

    return cell;

}

1 个答案:

答案 0 :(得分:0)

我的应用程序中有一个不使用Web Socket的聊天(我们没有时间实现它),所以我们要做的是使用通知中心刷新UITableView。

在AppDelegate中我有这段代码:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTheTable" object:nil];
}

然后在我的聊天课中,我有这段代码在viewDidLoad中注册通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTable:) name:@"reloadTheTable" object:nil];

然后选择器调用服务器并刷新显示的数据:

- (void)reloadTable:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self checkJson]; //This function loads the data and when it finish calls another method call loadTable
}

- (void)loadTable {
    [_tvTable reloadData]; //this simply reload your UITableView
}

当应用程序到达前台时,我也使用此技术重新加载:

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTheTable" object:nil];
}

我希望这会对你有所帮助。