URL连接后无法将Web服务数据传递给另一个viewcontroller

时间:2014-10-21 19:16:32

标签: ios objective-c segue viewcontroller

我想传递从以下网址收到的json数据并传递"用户名"数据到SecondViewController。我只想传递数据,何时连接成功。

我遇到以下问题:

  1. 无论URL是对还是错,我都会被定向到SecondViewController。我只想在连接成功并获取数据时转到SecondViewController。

  2. 当我在URL连接代码中放入以下行时,我无法在SecondViewController上接收数据:

  3. SecondViewController * destination=[segue destinationViewController];

    destination.displayName=[info objectForKey:@"username"];

    如果我之前放置了以下代码,NSURL可以工作,我在SecondViewController中看到了这条消息。但我通过destination.displayName=@"Testing Message"

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
        NSURL *url = [NSURL URLWithString:@"http://localhost/?user_id=1"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[NSOperationQueue mainQueue]
                               completionHandler:^(NSURLResponse *response,
                                                   NSData *data, NSError *connectionError)
         {
             if (data.length > 0 && connectionError == nil)
             {
                 NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data
                                                                          options:0
                                                                         error:NULL];
                 //this is my second view controller
                 SecondViewController * destination=[segue destinationViewController];
    
                 destination.displayName=[info objectForKey:@"username"];
    
             }//if connected
    
         }];//end of connection
    
    }//end of prepareforsegue
    

    实现这一目标的最佳方法是什么?将URL连接代码放在prepareForSegue中是否正确?

1 个答案:

答案 0 :(得分:1)

我建议这个解决方案:

- (void)fetchRequest {
    NSURL *url = [NSURL URLWithString:@"http://localhost/?user_id=1"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data.length > 0 && !connectionError) {
            NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            [self performSegueWithIdentifier:@"SecondViewController" sender:info];
        }//if connected
    }];//end of connection
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"SecondViewController"]) {
        if ([sender isKindOfClass:[NSDictionary class]]) {
            //this is my second view controller
            SecondViewController * destination = [segue destinationViewController];
            destination.displayName=[sender objectForKey:@"username"];
        } // end of check on Sender Type
    } // end identifier check ..
}//end of prepareforsegue

祝你的应用好运。