2014-01-17 3 views
-1

안녕하세요, AFNetworking Framework을 구현하려고합니다. AFNetworking 프레임 워크를 사용하여 json 데이터를 검색하려고합니다. 하지만 AFNetworking 프레임 워크를 사용하여 JSON 데이터를 검색하는 방법을 모른다. 제발 어떤 몸이라도 안내 해줘. https://github.com/AFNetworking/AFNetworking 및 코드 아래 사용 :json 파싱을 AFNetworking으로 만드는 방법

-(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 가져올 수 있습니다

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 이 내 코드입니다 * 오류, ID JSON) { }]; 당신이 AFJSONRequestOperation, 그것은 네트워크를 통해 데이터를 가져 와서 pasred JSON 응답을 제공 할 수 있습니다 당신을 AFNetworking에서

[operation start]; 
+0

감사가 의미 - (무효) connectionDidFinishLoading : (있는 NSURLConnection *) 연결하는 부분은 동일 또는 변경 사항은이 ? – user2930730

+0

위의 업데이트 된 답변을 확인하십시오. –

+0

"선언되지 않은 식별자 사용"과 같은 오류가 발생했습니다 .AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest : 요청 성공 :^(NSURLRequest * 요청, NSHTTPURLResponse * 응답, ID JSON) ........ 내 .m 파일을 가져온 클래스의 유형 – user2930730

0

. 내 code.i에 같은 일부 남아있는 내 코드에 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]; 
관련 문제