ios,如何向单独的VC发送异步通知?

时间:2015-01-29 01:20:31

标签: objective-c sockets asynchronous

现在我正在使用NSNotificationCenter从我的套接字单例发送同步通知到视图控制器。但是,这会引起问题。在viewDidAppear上,我的观察者没有收到通知。我怎么能异步这样做?我设法通过在我的VC的viewDidLoad中发布通知来让VC填充来自我的套接字的数据,但这个dosnt似乎是正确的做法。

我的应用程序是如何工作的,我向套接字发出数据,然后套接字发出一个名为" initialize"的回叫,在此通知后,我推送到新的VC。这可能导致问题吗?

-(void)receiveInitializeNotification:(NSNotification *)notificaiton
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self performSegueWithIdentifier:@"toSetListRoomVC" sender:self];
    });
}

当前代码:套接字

- (void)startSocketWithHost:(NSString *)host;{

    [SIOSocket socketWithHost:host response:^(SIOSocket *socket) {

        self.socket = socket;


        //Send a message to RoomCode controler to notify the reciever that the user has enetered a correct code and can enter the specific setList room.
        [self.socket on:@"initialize" callback:^(NSArray *args) {

            NSDictionary *socketIdDict = [args objectAtIndex:0];
            NSString *socketID = [socketIdDict objectForKey:@"socket"];
            self.socketID = socketID;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"initialize" object:nil];

        }];

        //on Callback for events related to updates with the song queue.
        [self.socket on:@"q_update_B" callback:^(NSArray *args) {

            NSLog(@"qUpdateB has been emitted");
            NSArray *tracks = [args objectAtIndex:0];
            self.setListTracks = tracks;

            [self performSelectorOnMainThread:@selector(postQUpdateBNotification) withObject:nil waitUntilDone:YES] ;
        }];

        [self.socket on:@"current_artist_B" callback:^(NSArray *args) {

            self.currentArtist = [args objectAtIndex:0];

            [self performSelectorOnMainThread:@selector(postCurrentArtistBNotification) withObject:nil waitUntilDone:YES] ;

        }];

接收"初始化"通知。

-(void)receiveInitializeNotification:(NSNotification *)notificaiton
{
        [self performSegueWithIdentifier:@"toSetListRoomVC" sender:self];
}

在SetListVC中接收qUpdateB

- (void)receiveUpdateBNotification:(NSNotification *)notification
{
    NSLog(@"Recieved update B");
    NSArray *recievedtracks = [[SocketKeeperSingleton sharedInstance]setListTracks];
    self.tracks = recievedtracks;
    [self.tableView reloadData];

}

我的" qUpdateB已被安排"被segue称为新VC。 但是,新VC中未收到通知。 如果我添加

[[NSNotificationCenter defaultCenter] postNotificationName:@"currentArtistB" object:nil];

对于我的SetlistVC以及观察者,它将按预期工作,但这个dosnt似乎是正确的。

1 个答案:

答案 0 :(得分:1)

套接字正在网络线程上工作,不是吗?如果您在该线程中发布通知,接收方将在网络线程上获得通知。但是,您只能在主线程上操作UI。所以你真正需要的是在主线程上发布通知,这样你的视图控制器就可以在主线程上接收通知。

[self performSelectorOnMainThread:@selector(postNotification) withObject:nil waitUntilDone:YES] ;

- (void)postNotification {
  [[NSNotificationCenter defaultCenter] postNotificationName:@"yourEventName" object:self] ;
}