如何使用异步NSURLConnection将数据传递到View Controller

时间:2015-08-21 22:37:47

标签: ios objective-c json asynchronous

我有View Controller,我从web获取数据,解析Json,并将字符串传递给另一个View Controller。如果我使用同步NSURLConnection,一切正常。

但是如果我切换到异步,那么方法(void)prepareForSegue:(UIStoryboardSegue *)会在解析我从网上获得的Json数据之前调用。

跳过_jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]方法。有什么想法吗?预先感谢您的帮助。这是我的代码:

-(void)getClothInfo {
    NSString *allowedClothSizeToServer = [_foreignSizeToServer     stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *getDataURL = [NSString stringWithFormat:@"http://xsdcompany.com/jsoncloth.php?foreignSize=%@",allowedClothSizeToServer];
    NSURL *url = [NSURL URLWithString:getDataURL];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler: ^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        if (connectionError) {
            [self showAlertWithMessage2:@"Server is Unavialable"];
        } else {
            _jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

            //Loop trough our jsonArray
            for (int i=0; i<_jsonArray.count; i++) {
                //Create our size object
                _usSizeFromServer = [[_jsonArray objectAtIndex:i] objectForKey:@"usSizeCloth"];
            }
        }
    }];
}

- (IBAction)getIt:(id)sender {
    // Validate data
    if ([self validData] == NO)
    {
         return;
    }

    [self getClothInfo];
    [self showNextViewController];
}

-(void) showNextViewController {
    [self performSegueWithIdentifier:@"GetCLothInfo" sender:nil];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    ResultViewController *resultViewController = [segue destinationViewController];
    resultViewController.foreignSizeToResult = [[NSString alloc] initWithFormat:@"%@ size for %@ is %@", [_pickerProcessor selectedCountry].countryName, [_pickerProcessor selectedCloth].clothName, [_pickerProcessor selectedSize].sizeName];
    resultViewController.dataForUsSize = [[NSString alloc] initWithFormat:@"Your US size for %@ is %@", [_pickerProcessor selectedCloth].clothName, _usSizeFromServer];
}

3 个答案:

答案 0 :(得分:1)

您有两种选择。您可以从showNextViewController方法中的完成块调用getClothInfo。或者更好的是,在getClothInfo方法中添加完成块参数,然后从NSURLConnection的完成块中调用该参数。

这样的事情:

-(void)getClothInfo:(void ^(void))completion {
    NSString *allowedClothSizeToServer = [_foreignSizeToServer     stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *getDataURL = [NSString stringWithFormat:@"http://xsdcompany.com/jsoncloth.php?foreignSize=%@",allowedClothSizeToServer];
    NSURL *url = [NSURL URLWithString:getDataURL];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler: ^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        if (connectionError) {
            [self showAlertWithMessage2:@"Server is Unavialable"];
        } else {
            _jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

            //Loop trough our jsonArray
            for (int i=0; i<_jsonArray.count; i++) {
                //Create our size object
                _usSizeFromServer = [[_jsonArray objectAtIndex:i] objectForKey:@"usSizeCloth"];
            }

            if (completion) {
                dispatch_async(dispatch_get_main_queue(), ^{
                     completion();
                });
            }
        }
    }];
}

- (IBAction)getIt:(id)sender {
    // Validate data
    if ([self validData] == NO)
    {
         return;
    }

    [self getClothInfo:^ {
        [self showNextViewController];
    }];
}

答案 1 :(得分:0)

您似乎希望在segue之前下载json数据,在这种情况下同步NSURLConnection是有意义的

当您进行异步NSURLConnection调用时,这意味着将执行后续代码(在本例中为performSegue)。

如果您可以解释您的预期行为

,将会有所帮助

答案 2 :(得分:0)

使用

从连接获取响应时注册通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"ResponseObtained" object:_jsonArray];

在第二个视图控制器中添加观察者通知

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

您可以使用

访问handleResponse方法中的_jasonArray
- (void)handleResponse:(NSNotification *)notif{

    NSDictionary *result = [notif object]; }