在請求前的VC上,聲明一個屬性(和@synthesize)來保留網絡請求的結果。
@property (nonatomic, strong) NSData *responseData;
然後在任何事件觸發的要求,象這樣開始:
NSString *urlString = /* form the get request */
NSURL *url = [NSURL urlWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// consider doing some UI on this VC to indicate that you're working on a request
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!error) {
self.responseData = data;
// hide the "busy" UI
// now go to the next VC with the response
[self performSegueWithIdentifier:@"ThridVCSegue" sender:self];
}
}];
然後響應數據傳遞到第三VC這樣的:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:@"ThridVCSegue"]) {
ThirdViewController *vc = (ThirdViewController *)[segue destinationViewController];
[vc dataFromHTTPRequest:self.responseData];
}
}
這是假設你」將使用ARC,故事板,並定義該segue。 ThirdViewController需要一個公共方法來接受http響應數據。