繁体   English   中英

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

[英]How to pass data to the View Controller using asynchronous NSURLConnection

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

但是,如果我切换到异步模式,则在解析从Web获取的Json数据之前,将调用(void)prepareForSegue:(UIStoryboardSegue *)方法。

只需跳过_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];
}

您有两个选择。 您可以从getClothInfo方法内的完成块调用showNextViewController 或者更好的方法是,将一个完成代码块参数添加到您的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];
    }];
}

似乎您想在序列化之前下载json数据,在这种情况下,同步NSURLConnection很有意义

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

如果您能解释一下您的预期行为是有帮助的

使用以下方法从连接获得响应时注册通知

[[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]; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM