在请求之前的 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 响应数据。