2016-01-13 18 views
0

我有一個ViewController在那一個UIImage和兩個UITextField的一個UITableView中,我想打印數據。這些數據來自api。如何在一個UIViewController中維護兩個api?

從第一個API我想顯示UIImage和UITextField的數據。 從第二個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

+0

爲什麼你不使用NSURLSession? –

回答

1

使用AFNetworking 3.0從GitHub。並呼籲在第一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); 
}]; 
0

我會建議與AFNetworking而不是嵌套調用API一起使用PromiseKit - 代碼保持清潔和可讀性。請參閱Chaining promises部分。

相關問題