如何在一个UIViewController中维护两个api?

时间:2016-01-13 07:27:28

标签: ios json uitableview

我在一个UIImage中有一个ViewController和两个UITextField的UITableView,我想要打印数据。来自api的数据。

从第一个api我想显示UIImage和UITextField的数据。 从Second Api将数据加载到UITableView中。怎么办?

到目前为止我试过这个

-(void)viewDidLoad
{
[super viewDidLoad];
NSString *urlString = [NSString stringWithFormat:@"API"];
NSString *jsonString = @"";
NSData *myJSONData =[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:myJSONData]];
[request setHTTPBody:body];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
if(str.length > 0){
    NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]);
    mainBannerArray =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
}
else{
    NSLog(@"Error");
}
} 

这是我的连接代表方法。

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
myDataQA = [[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[myDataQA appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if ((NSNull *)myDataQA != [NSNull null])
{
    if(myDataQA.length > 0)
    {
        mainBannerArray =[NSJSONSerialization JSONObjectWithData:myDataQA options:NSJSONReadingAllowFragments error:nil];
    }
}

我的屏幕就像这样

enter image description here

2 个答案:

答案 0 :(得分:1)

使用Github的AFNetworking 3.0。并在第一个API的成功块中调用第二个api,如下所示,

NSString *urlString = [NSString stringWithFormat:@"API"]
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// this for Image and Textfield
[manager GET:urlString parameters:nil progress:nil    success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
   // Load image and text field

   // And then call sencod url
   AFHTTPSessionManager *manager2 = [AFHTTPSessionManager manager];
   [manager2 GET:link2 parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
       NSLog(@"JSON: %@", responseObject);
      // reload the tableview
   } failure:^(NSURLSessionTask *operation, NSError *error) {
       NSLog(@"Error: %@", error);
   }]; 
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

答案 1 :(得分:0)

我建议将PromiseKit与AFNetworking一起使用,而不是嵌套的API调用 - 代码仍然清晰可读。请参阅Chaining promises部分。