2014-01-17 53 views
-1

Hi iam試圖實現AFNetworking Framework。我想使用AFNetworking框架來檢索json數據。但我不知道如何使用AFNetworking框架來檢索json數據。請任何機構指導我。 這是我的代碼:如何使用AFNetworking進行json解析

-(void)ViewDidLoad 

{ 

    userid=[[NSUserDefaults standardUserDefaults]valueForKey:@"user_id"]; 

    encryptpwd=[[NSUserDefaults standardUserDefaults]valueForKey:@"Encrypt_Psw"]; 

    id=[[NSUserDefaults standardUserDefaults]valueForKey:@"comm_id"]; 

    NSString *strJson=[NSString stringWithFormat:@"userId=%@&encryptPassword=%@&commId=%@",userid,encryptpwd,id]; 

    NSString *strlength=[NSString stringWithFormat:@"%d",[strJson length]]; 

    NSURL *url=[NSURL URLWithString:@「My URL」]; 

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url]; 

    [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"]; 

    [request addValue:strlength forHTTPHeaderField:@"Content-Length"]; 

    NSData *requestData=[strJson dataUsingEncoding:NSUTF8StringEncoding]; 

    [request setHTTPBody:requestData]; 

    [request setHTTPMethod:@"Post"]; 

    [[NSURLConnection alloc]initWithRequest:request delegate:self]; 

} 


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 

{ 

    responseData=[[NSMutableData alloc]init]; 

} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 

{ 

    [responseData appendData:data]; 

} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 

{ 

    [UIApplication sharedApplication].networkActivityIndicatorVisible=YES; 

    NSError *err; 

    NSString *strResponse=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding]; 

    NSLog(@"response is %@",strResponse); 

    dit=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&err]; 

    NSArray *arrResults = [dit valueForKey:@"class_mst"]; 

    listOfObjects = [NSMutableArray array]; 

    for(dictRes in arrResults) 

    { 

     Attributes *at = [[Attributes alloc]init]; 

     at.classimage=[dictRes valueForKey:@"image_name"]; 

     at.classname=[dictRes valueForKey:@"class_title"]; 

     [listOfObjects addObject:at]; 

    } 

    [tableView reloadData]; 

} 


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 

{ 

    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO; 

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection" message:@"Please ensure you have internet connection" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 

    [alert show]; 

} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 

{ 

    return [listOfObjects count]; 

} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

{ 

    static NSString *[email protected]"cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; 

    if (cell == nil) 

    { 

     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier]; 

    } 

    UIImageView *imageView =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 300, 80)]; 

    imageView.tag = 100; 

    [cell.contentView addSubview:imageView]; 

    UILabel *classtitle=[[UILabel alloc]initWithFrame:CGRectMake(5, 120, 200, 20)]; 

    classtitle.highlightedTextColor=[UIColor clearColor]; 

    classtitle.font=[UIFont systemFontOfSize:12.0]; 

    [cell.contentView addSubview:classtitle]; 

    Attributes *att = [listOfObjects objectAtIndex:indexPath.row]; 

    NSString *strf=att.classname; 

    classtitle.text=strf; 

    str=att.classimage; 

    [email protected]「image URL」; 

    UIImageView *cellImageView = [cell.contentView viewWithTag:100]; 

    // cellImageView.image = nil; 

    if(str!=nil) 

    { 

     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 

     dispatch_async(queue, ^(void) 

     { 


      NSString *imageStr = [url stringByAppendingString:str]; 
      UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageStr]]]; 

      dispatch_async(dispatch_get_main_queue(), ^{ 

      cellImageView.image = image; 

     }); 

     }); 

    } 

    return cell; 

} 

回答

0

您可以導入從以下鏈接AFNetworking庫:https://github.com/AFNetworking/AFNetworking 並使用下面的代碼:

NSURL *url = [[NSURL alloc] initWithString:@"YOURURL"]; 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; 
[request setHTTPMethod:@"POST"]; 
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
NSString *strJson=[NSString stringWithFormat:@"userId=%@&encryptPassword=%@&commId=%@",userid,encryptpwd,id]; 
[request setHTTPBody:[strJson dataUsingEncoding:NSUTF8StringEncoding]]; 
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
    NSDictionary *dict = [[NSDictionary alloc] initWithDictionary:JSON]; 

    NSArray *arrResults = [dict valueForKey:@"class_mst"]; 

    listOfObjects = [NSMutableArray array]; 

    for(dictRes in arrResults) 

    { 

    Attributes *at = [[Attributes alloc]init]; 

    at.classimage=[dictRes valueForKey:@"image_name"]; 

    at.classname=[dictRes valueForKey:@"class_title"]; 

    [listOfObjects addObject:at]; 

    } 

    [tableView reloadData]; 

}失敗:^(的NSURLRequest *要求,NSHTTPURLResponse *響應,NSError * error,id JSON){ }];

[operation start]; 
+0

感謝有沒有在我的code.i的意思是 - (無效)connectionDidFinishLoading:(NSURLConnection的*)連接的部分是相同或任何變化都存在? – user2930730

+0

請檢查我上面更新的答案。 –

+0

我得到錯誤,像「使用未聲明的標識符」這行代碼..AFJSONRequestOperation *操作= [AFJSONRequestOperation JSONRequestOperationWithRequest:請求成功:^(NSURLRequest *請求,NSHTTPURLResponse *響應,ID JSON)........ 。什麼類型的類導入了我的.m文件 – user2930730

0

在AFNetworking您可以在AFJSONRequestOperation,它通過網絡獲取數據並給pasred JSON響應。您response.According我的代碼剩餘部分相同或任何改變感謝

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 

      //it give parse json data 
      NSDictionary *dict = [[NSDictionary alloc] initWithDictionary:JSON]; 

     } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 

     }]; 

     [operation start];