Xcode HTTP GET请求视图之间的请求

时间:2012-10-11 19:03:34

标签: iphone xcode http geolocation xmlhttprequest

我对xcode非常陌生并且知道一些编码,但我正在尝试在我的应用程序中实现api的使用。这是我想要做的事情。

  • 从我的第一个viewcontroller中获取地理位置。
  • 从我的第二个viewcontroller中获取几个变量。
  • 使用所有收集的变量并生成我的HTTP REQUEST
  • 在我的第三个viewcontroller上显示返回的数据。

我已经设置了我的viewcontrollers并让我的第一个viewcontroller找到了我。

任何帮助都会受到很多关注。我在山狮上使用最新的xcode,这是需要发送的请求http://yourtaximeter.com/api/?key=...

2 个答案:

答案 0 :(得分:0)

不要在viewcontrollers中实现逻辑,为所有连接使用另一个类。例如,“ConnectionManager”类或“DataManager”类。查看this问题。

您还可以查看AFNetworking并使用他们的AFHTTPClient为您自己的api创建子类。

答案 1 :(得分:0)

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

相关问题