2012-03-07 2 views
2

코어 데이터가있는 프로젝트를 만들고 있습니다.코어 데이터를 사용하여 로그인 ID 및 비밀번호 iOS

내 첫 번째보기는 테이블보기 컨트롤러에서 로그인/암호입니다.

사용자가 완료되면, 내 앱이 로그인 및 비밀번호 텍스트 입력란과 속성 (userid 및 비밀번호)을 비교 한 다음 해당 사용자와 관련된 정보가 포함 된 다른보기를 표시합니다 (1 1) 관계.

누구든지 로그인 암호의 유효성을 검사하고 해당 사용자와 관련된 정보 만 표시하는 방법을 도울 수 있습니까?

도움이 될 것입니다. 나는 이것에 완전히 새로운 것이다.

답변

3

당신은 (당신이 당신의 특정 요구에 맞게이를 수정해야합니다 그 실체에 대해 가져 오기 요청을 만들 필요가 : 당신이 결과에 무엇을해야합니까 ...

NSFetchRequest *request= [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:context]; 
NSPredicate *predicate =[NSPredicate predicateWithFormat:@"username==%@ AND password==%@",self.UsernameTextField.Text, self.PasswordTextField.Text]; 
[request setEntity:entity]; 
[request setPredicate:predicate]; 

을 (NSArray를)

+0

덕분에 입력 ... 당신은 requ에 [무엇을 말해 줄 수 est setEntity : 엔터티]; [요청 setPredicate : 조건 자]; 평균??? 어떻게 그들을 대상보기 컨트롤러에 연결하는 데 사용할 수 있습니까? – user1253637

+0

이 시점에서 가장 좋은 점은 여기에 대한 자습서를 살펴 보는 것입니다. Ray Wenderlich는 기본적인 Core Data에 훌륭한 것들을 가지고 있으며, iTunesU Stanford 과정도 정말 훌륭합니다. 다른 옵션은 교육비를 지불하는 것입니다. Lynda.com은 내 의견으로는 좋은 곳입니다. –

0
// First view controller 
#import "ViewController.h" 
#import "ViewController6578.h" 
#import "AppDelegate.h" 
#import <CoreData/CoreData.h> 
@interface ViewController()<UITextFieldDelegate> 
{ 
    NSArray *user; 
} 
- (IBAction)btt_reg:(id)sender; 
@end 
@implementation ViewController 
- (NSManagedObjectContext *)managedObjectContext 
{ 
    NSManagedObjectContext *context = nil; 

    id delegate = [[UIApplication sharedApplication] delegate]; 

    if ([delegate performSelector:@selector(managedObjectContext)]) { 

     context = [delegate managedObjectContext]; 

    } 

    return context; 
} 

- (void)viewDidLoad { 

    [super viewDidLoad]; 

    // Do any additional setup after loading the view, typically from a nib. 

} 



- (void)didReceiveMemoryWarning { 

    [super didReceiveMemoryWarning]; 

    // Dispose of any resources that can be recreated. 

} 

- (void)textFieldDidEndEditing:(UITextField *)textField 

{ 

// AppDelegate *appDelegate = 

//  [[UIApplication sharedApplication] delegate]; 
     NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; 

    NSFetchRequest *request= [[NSFetchRequest alloc] init]; 

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"LogIn" inManagedObjectContext:managedObjectContext]; 

    [request setEntity:entity]; 

    NSPredicate *predicate =[NSPredicate predicateWithFormat:@"userName==%@",self.txt_user.text]; 

    [request setPredicate:predicate]; 

    NSManagedObject *manage = nil; 

    NSError *error; 

    user=[managedObjectContext executeFetchRequest:request error:&error]; 

    if([user count]==0) 
    { 

     NSLog(@"user and password"); 

    } 

    else 

    { 

     manage =user[0]; 

     _txt_pass.text = [manage valueForKey:@"password"]; 

    } 
} 

- (IBAction)btt_log:(id)sender { 

    if((_txt_user.text.length == 0) || (_txt_pass.text.length==0)) 

    { 

     NSLog(@"enter username and password"); 

    } 

    else{ 

     NSLog(@"%@,Login successfull",_txt_user.text); 

    } 
} 

- (IBAction)btt_reg:(id)sender { 
    ViewController6578 *vc2 = [self.storyboard instantiateViewControllerWithIdentifier:@"ndot"]; 

    [self.navigationController pushViewController:vc2 animated:YES]; 

} 

@end 

//second view controller 

#import "ViewController6578.h" 

#import "AppDelegate.h" 

#import <CoreData/CoreData.h> 

@interface ViewController6578()<UITextFieldDelegate> 

@end 

@implementation ViewController6578 

- (NSManagedObjectContext *)managedObjectContext { 

    NSManagedObjectContext *context = nil; 

    id delegate = [[UIApplication sharedApplication] delegate]; 

    if ([delegate performSelector:@selector(managedObjectContext)]) { 

     context = [delegate managedObjectContext]; 

    } 

    return context; 

} 

- (void)viewDidLoad { 

    [super viewDidLoad]; 

    // Do any additional setup after loading the view. 

} 

- (void)didReceiveMemoryWarning { 

    [super didReceiveMemoryWarning]; 

    // Dispose of any resources that can be recreated. 

} 

/* 

#pragma mark - Navigation 



// In a storyboard-based application, you will often want to do a little preparation before navigation 

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 

    // Get the new view controller using [segue destinationViewController]. 

    // Pass the selected object to the new view controller. 

} 

*/ 

#pragma mark-delegate 

- (BOOL)textFieldShouldReturn:(UITextField *)textField 

{ 

    [textField becomeFirstResponder]; 

    if(textField == _txt_user) 

    { 

     [_txt_pass becomeFirstResponder]; 

    } 

    else if(textField == _txt_pass) 

    { 

     [_txt_email becomeFirstResponder]; 

    } 

    else if(textField == _txt_email) 

    { 

     [_txt_email becomeFirstResponder]; 

    } 

    else 

    { 

     [_txt_email resignFirstResponder]; 

    } 

    return YES;  

} 

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 

{ 

    if (textField == _txt_user) 

    { 

     NSString *user =[_txt_user.text stringByReplacingCharactersInRange:range withString:string]; 

     NSString *userRegex = @"^[A-Z0-9a-z]{6,10}$"; 

     NSPredicate *userTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", userRegex]; 

     if ([userTest evaluateWithObject:user] == YES) 

     { 

      _lbl1.text [email protected]""; 

     } 

     else{ 

      _lbl1.text [email protected]"not valid"; 

     } 

    } 

    if(textField ==_txt_pass) 

    { 

     NSString *pass =[_txt_pass.text stringByReplacingCharactersInRange:range withString:string]; 



     NSString *passRegex [email protected]"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,16}$"; 

     NSPredicate *passTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passRegex]; 

     if ([passTest evaluateWithObject:pass] == YES) 

     { 

      _lbl2.text [email protected]""; 

     } 

     else{ 

      _lbl2.text [email protected]"not valid"; 

     } 
    } 

    if(textField ==_txt_email) 

    { 

     NSString *email =[_txt_email.text stringByReplacingCharactersInRange:range withString:string]; 

     NSString *emailRegex = @"[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,10}"; 

     NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 

     if ([emailTest evaluateWithObject:email] == YES) 

     { 

      _lbl3.text [email protected]""; 

     } 

     else{ 

      _lbl3.text [email protected]"not valid"; 

     } 

    } 

    return YES; 

} 

- (IBAction)btt_save:(id)sender 

{ 

    if((_txt_user.text.length==0) || (_txt_pass.text.length==0) || (_txt_email.text.length==0)) 

    { 

     UIAlertController *alert =[UIAlertController alertControllerWithTitle:@"title" message:@"please enter user,password,email" preferredStyle:UIAlertViewStyleDefault]; 

     UIAlertAction* yesButton = [UIAlertAction 

            actionWithTitle:@"Yes, please" 

            style:UIAlertActionStyleDefault 

            handler:^(UIAlertAction * action) 

            { 
            }]; 

     UIAlertAction* cancelButton = [UIAlertAction 

             actionWithTitle:@"No, thanks" 

             style:UIAlertActionStyleDefault 

             handler:^(UIAlertAction * action) 

             { 

             }]; 

     [alert addAction:yesButton]; 

     [alert addAction:cancelButton]; 

     [self presentViewController:alert animated:yesButton completion:nil]; 

    } 

    else 

    { 


    NSManagedObjectContext *context = [self managedObjectContext]; 

    // Create a new managed object 

    NSManagedObject *details = [NSEntityDescription insertNewObjectForEntityForName:@"LogIn" inManagedObjectContext:context]; 

    [details setValue:self.txt_user.text forKey:@"userName"]; 

    [details setValue:self.txt_pass.text forKey:@"password"]; 

    [details setValue:self.txt_email.text forKey:@"emailAddress"]; 

    NSLog(@"12334%@",details); 

    NSError *error = nil; 

    _txt_user.text [email protected]""; 

    _txt_pass.text [email protected]""; 

    _txt_email.text [email protected]""; 
    // Save the object to persistent store 
    if (![context save:&error]) { 

     NSLog(@"Can't Save! %@ ",error .localizedDescription); 

    } 

} 

    [self.navigationController popViewControllerAnimated:YES]; 

} 

- (IBAction)btt_cancel:(id)sender { 

    [self.navigationController popViewControllerAnimated:YES]; 

} 


@end 
+0

코드에 설명을 넣어주세요. –

0
//first view controller 

#import "ViewController.h" 

#import "SecondViewController.h" 

#import "SecondTableViewCell.h" 

#import "AppDelegate.h" 





@interface ViewController()<UITableViewDataSource,UITableViewDelegate> 

@property(strong)NSMutableArray *company; 



@end 



@implementation ViewController 



- (NSManagedObjectContext *)managedObjectContext 

{ 

    NSManagedObjectContext *context = nil; 

    id delegate = [[UIApplication sharedApplication] delegate]; 

    if ([delegate performSelector:@selector(managedObjectContext)]) { 

     context = [delegate managedObjectContext]; 

    } 

    return context; 

} 



- (void)viewDidLoad { 

    [super viewDidLoad]; 

    // Do any additional setup after loading the view, typically from a nib. 

} 



- (void)didReceiveMemoryWarning { 

    [super didReceiveMemoryWarning]; 

    // Dispose of any resources that can be recreated. 

} 



- (void)viewDidAppear:(BOOL)animated 

{ 

    [super viewDidAppear:animated]; 



    // Fetch the devices from persistent data store 

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; 

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"CompanyDetails"]; 

    self.company = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy]; 



    [self.tableview reloadData]; 

} 



#pragma mark-datasource 



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 

{ 

    // Return the number of sections. 

    return 1; 

} 



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

{ 

    // Return the number of rows in the section. 

    return self.company.count; 

} 



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

{ 

    static NSString *CellIdentifier = @"sri"; 

    SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 



    // Configure the cell... 

    NSManagedObject *device = [self.company 

           objectAtIndex:indexPath.row]; 



    cell.lbl_c.text=[NSString stringWithFormat:@"%@", [device valueForKey:@"companyName"]]; 



    cell.lbl_e .text=[NSString stringWithFormat:@"%@" , [device valueForKey:@"empName"]]; 



    cell.lbl_s .text=[NSString stringWithFormat:@"%@", [device valueForKey:@"salary"]]; 

    cell.img_g.image =[UIImage imageWithData:[device valueForKey:@"companyImage"]]; 



    return cell; 

} 



// delete 



- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 

{ 

    // Return NO if you do not want the specified item to be editable. 

    return YES; 

} 





- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 

{ 

    NSManagedObjectContext *context = [self managedObjectContext]; 



    if (editingStyle == UITableViewCellEditingStyleDelete) { 

     // Delete object from database 

     [context deleteObject:[self.company 

           objectAtIndex:indexPath.row]]; 



     NSError *error = nil; 

     if (![context save:&error]) { 

      NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]); 

      return; 

     } 



     // Remove device from table view 

     [self.company removeObjectAtIndex:indexPath.row]; 

     [self.tableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 

    } 

} 



- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 

{ 

    if ([[segue identifier] isEqualToString:@"segue"]) { 

     NSManagedObject *selectedDevice = [self.company objectAtIndex:[[self.tableview indexPathForSelectedRow] row]]; 

     SecondViewController *vc2 = segue.destinationViewController; 

     vc2.device = selectedDevice; 

    } 

} 



@end 



//second view controller 



#import "SecondViewController.h" 

#import "AppDelegate.h" 

#import <CoreData/CoreData.h> 







@interface SecondViewController()<UINavigationControllerDelegate,UIImagePickerControllerDelegate> 



@end 



@implementation SecondViewController 

@synthesize device; 



-(NSManagedObjectContext *)managedObjectContext 

{ 

    NSManagedObjectContext *context = nil; 



    id delegate = [[UIApplication sharedApplication] delegate]; 

    if ([delegate performSelector:@selector(managedObjectContext)]) { 

     context = [delegate managedObjectContext]; 

    } 

    return context; 

} 





- (void)viewDidLoad { 

    [super viewDidLoad]; 



    if (self.device) { 

     [self.txt_c setText:[self.device valueForKey:@"companyName"]]; 

     [self.txt_e setText:[self.device valueForKey:@"empName"]]; 

     [self.txt_s setText:[self.device valueForKey:@"salary"]]; 

     self.img.image = [UIImage imageWithData:[self.device valueForKey:@"companyImage"]]; 



//  self.txt_stdname.text = [NSString stringWithFormat:@"%@",[self.obj valueForKey:@"studentName"]]; 

//   

//  self.txt_strrollno.text = [NSString stringWithFormat:@"%@",[self.obj valueForKey:@"studentRollno"]]; 

//   

//  self.txt_stddept.text = [NSString stringWithFormat:@"%@",[self.obj valueForKey:@"studentDepartment"]]; 





    } 



    // Do any additional setup after loading the view. 

} 



- (void)didReceiveMemoryWarning { 

    [super didReceiveMemoryWarning]; 

    // Dispose of any resources that can be recreated. 

} 



/* 

#pragma mark - Navigation 



// In a storyboard-based application, you will often want to do a little preparation before navigation 

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 

    // Get the new view controller using [segue destinationViewController]. 

    // Pass the selected object to the new view controller. 

} 

*/ 



- (IBAction)btt_save:(id)sender { 



    NSManagedObjectContext *context = [self managedObjectContext]; 

    if(self.device) 

    { 

     [device setValue:self.txt_c.text forKey:@"companyName"]; 

     [device setValue:self.txt_e.text forKey:@"empName"]; 

     [device setValue:self.txt_s.text forKey:@"salary"]; 





     NSData *imgdata = UIImageJPEGRepresentation(self.img.image, 0.0); 

     [device setValue:imgdata forKey:@"companyImage"]; 





    } 

    else 

    { 



    NSManagedObject *comdetails = [NSEntityDescription insertNewObjectForEntityForName:@"CompanyDetails" inManagedObjectContext:context]; 

    [comdetails setValue:self.txt_c.text forKey:@"companyName"]; 

    [comdetails setValue:self.txt_e.text forKey:@"empName"]; 

    [comdetails setValue:self.txt_s.text forKey:@"salary"]; 



    NSData *imgdata = UIImageJPEGRepresentation(self.img.image, 0.0); 

    [comdetails setValue:imgdata forKey:@"companyImage"]; 

    } 



    NSError *error = nil; 

    // Save the object to persistent store 

    if (![context save:&error]) { 

     NSLog(@"Can't Save! %@ ", error.localizedDescription); 

    } 

    [self.navigationController popViewControllerAnimated:YES]; 

} 



- (IBAction)btt_gallery:(id)sender { 



    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init]; 

    imagePicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary; 

    imagePicker.delegate = self; 

    [self presentViewController:imagePicker animated:YES completion:nil]; 





} 



#pragma mark UIImagePickerControllerDelegate 







- (void) imagePickerController:(UIImagePickerController *)picker 



     didFinishPickingImage:(UIImage *)image 



        editingInfo:(NSDictionary *)editingInfo 



{ 



    self.img.image = image; 



    [self dismissModalViewControllerAnimated:YES]; 



} 







- (IBAction)btt_cancel:(id)sender { 



    [self.navigationController popViewControllerAnimated:YES]; 

} 


@end 
-1
#import "ViewController.h" 

#import "CollectionViewCell1234.h" 

#import "ViewController6778.h" 







@interface ViewController()<NSURLConnectionDelegate,NSURLConnectionDataDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UINavigationControllerDelegate> 



@property (nonatomic ,strong)NSData *resultdata; 

@property (nonatomic,strong)NSMutableArray *array1; 



@end 



@implementation ViewController 



- (void)viewDidLoad { 

    [super viewDidLoad]; 

    // Do any additional setup after loading the view, typically from a nib. 

    [self webserviceCallingUsingGETMethod]; 

    _collectionview.backgroundColor = [UIColor purpleColor]; 





} 



- (void)didReceiveMemoryWarning { 

    [super didReceiveMemoryWarning]; 

    // Dispose of any resources that can be recreated. 

} 

#pragma mark- delegate 

-(void)webserviceCallingUsingGETMethod 

{ 

NSString *stringurl = @"https://itunes.apple.com/search?"; 

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",stringurl]]; 

NSString *params = @"term=jack+johnson&entity=musicVideo"; 

NSData *postdata = [params dataUsingEncoding:NSUTF8StringEncoding]; 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init]; 

[request setURL:url]; 

[request setHTTPMethod:@"POST"]; 

[request setHTTPBody:postdata]; 

[NSURLConnection connectionWithRequest:request delegate:self]; 



    NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 



[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { 



    if (connectionError) { 

     NSLog(@"Error :%@", connectionError.localizedDescription); 

     return; 

    } 



    if (data) { 



     self.resultdata = data; 

     NSError *error = nil; 





     NSDictionary *result = [NSJSONSerialization JSONObjectWithData:_resultdata options:NSJSONReadingAllowFragments error:&error]; 



     NSLog(@"RESULT :%@", result); 



     NSArray *array = [result valueForKey:@"results"]; 

     _array1 =[[NSMutableArray alloc]init]; 

     _array1 = [NSMutableArray arrayWithArray:array]; 

     NSLog(@"122345%@",array); 



     dispatch_async(dispatch_get_main_queue(), ^{ 



      [_collectionview reloadData]; 

     }); 



    } 

}]; 





} 







#pragma mark-collectionview delegate 



- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView 

{ 

    return 1; 

} 





- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 

{ 

    return _array1.count; 

} 



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 

{ 

    NSString *nschool = @"sri"; 

    CollectionViewCell1234 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:nschool forIndexPath:indexPath]; 

    cell.imgview.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[[_array1 valueForKey:@"artworkUrl30"]objectAtIndex:indexPath.row]]]]]; 

    cell.backgroundColor = [UIColor greenColor]; 

    cell.lbl1.text = [[self.array1 valueForKey:@"wrapperType"]objectAtIndex:indexPath.row]; 

    cell.lbl2.text = [[self.array1 valueForKey:@"artistName"]objectAtIndex:indexPath.row]; 

    cell.lbl3.text = [[self.array1 valueForKey:@"releaseDate"]objectAtIndex:indexPath.row]; 

    cell.lbl4.text = [[self.array1 valueForKey:@"country"]objectAtIndex:indexPath.row]; 

    cell.lbl5.text = [[self.array1 valueForKey:@"currency"]objectAtIndex:indexPath.row]; 

    cell.lbl6.text = [[self.array1 valueForKey:@"trackName"]objectAtIndex:indexPath.row]; 

    cell.lbl7.text = [[self.array1 valueForKey:@"kind"]objectAtIndex:indexPath.row]; 





    NSInteger artid= [[[self.array1 valueForKey:@"artistId"]objectAtIndex:indexPath.row]integerValue]; 

    NSString *str1 =[NSString stringWithFormat:@"%ld",(long)artid]; 

    cell.lbl8.text = str1; 

    CGFloat cp = [[[self.array1 valueForKey:@"collectionPrice"]objectAtIndex:indexPath.row]floatValue]; 

    NSString *str4 = [NSString stringWithFormat:@"%3f",cp]; 

    cell.lbl9.text = str4; 

    cell.lbl10.text = [[self.array1 valueForKey:@"collectionExplicitness"]objectAtIndex:indexPath.row]; 

    cell.lbl11.text = [[self.array1 valueForKey:@"primaryGenreName"]objectAtIndex:indexPath.row]; 





    NSInteger tracknum = [[[self.array1 valueForKey:@"trackId"]objectAtIndex:indexPath.row]integerValue]; 

    NSString *str3 = [NSString stringWithFormat:@"%ld",(long)tracknum]; 

    cell.lbl12.text = str3; 

    cell.lbl13.text = [[self.array1 valueForKey:@"trackExplicitness"]objectAtIndex:indexPath.row]; 



    NSInteger tracknum1 =[[[self.array1 valueForKey:@"trackTimeMillis"]objectAtIndex:indexPath.row]integerValue]; 

    NSString *str2 = [NSString stringWithFormat:@"%ld",(long)tracknum1]; 



    cell.lbl14.text =str2; 

    return cell; 

} 

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 

{ 

    [self performSegueWithIdentifier:@"segue" sender:self]; 

} 



- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 

{ 

    if ([[segue identifier] isEqualToString:@"segue"]) 

    { 

     ViewController6778 *vc2 = [segue destinationViewController]; 

     vc2.img1.images ; 

    } 

} 

@end 
0
#import "ViewController.h" 
#import "secondTableViewCell.h" 
#import "SecondViewController.h" 

@interface ViewController()<NSURLConnectionDelegate,NSURLConnectionDataDelegate,UITableViewDelegate,UITableViewDataSource> 

@property(nonatomic,strong)NSData *get_data; 
@property(nonatomic,strong)NSMutableArray *result_array; 

@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    NSString *base_url = @"https://itunes.apple.com/lookup?id=909253&entity=album"; 

    NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"%@",base_url]]; 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init]; 
    [request setURL:url]; 
    [request setHTTPMethod:@"GET"]; 
    [NSURLConnection connectionWithRequest:request delegate:self]; 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 
#pragma mark- nsurlconnection delegate 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; 
{ 
    NSLog(@"%@",error.localizedDescription); 
} 
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response 
{ 

    NSLog(@"%@",response); 
} 
-(void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data 
{ 

    NSLog(@"88888%@",data); 

    if ([data length]) 
    { 
     self.get_data = [[NSData alloc]init]; 
     self.get_data =data; 
     NSLog(@"%@",self.get_data); 

    } 


} 
-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSError *error = nil; 

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.get_data options:NSJSONReadingMutableLeaves error:&error]; 
    NSLog(@"vijay%@",dict); 


    if (!error) 
    { 

     NSArray *array = [dict valueForKey:@"results"]; 
     NSLog(@"1212%@",array); 

     self.result_array = [[NSMutableArray alloc]init]; 

     self.result_array = [NSMutableArray arrayWithArray:array]; 

       dispatch_async(dispatch_get_main_queue(), ^{ 
        [_tableview reloadData]; 
       }); 
    } 


} 
#pragma mark -uitableview datasource 

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return self.result_array.count; 
} 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    secondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sri"]; 
    if (cell == nil) 
    { 
     cell = [[secondTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil]; 
    } 

    cell.lbl1.text = [[self.result_array valueForKey:@"wrapperType"]objectAtIndex:indexPath.row]; 
    cell.lbl2.text = [[self.result_array valueForKey:@"artistName"]objectAtIndex:indexPath.row]; 
    cell.lbl3.text = [[self.result_array valueForKey:@"primaryGenreName"]objectAtIndex:indexPath.row]; 

    // integer to string 
    NSInteger artid = [[[self.result_array valueForKey:@"artistId"]objectAtIndex:indexPath.row] integerValue]; 

    NSString *str = [NSString stringWithFormat:@"%ld",(long)artid]; 

//  NSInteger release = [[[self.result_array valueForKey:@"releaseDate"]objectAtIndex:indexPath.row] integerValue]; 
//  
//  NSString *str1 = [NSString stringWithFormat:@"%ld",(long)release]; 
    // 
// cell.lbl3.text = str; 
//// //  // float to string 
//  float a = [[[self.result_array valueForKey:@"collectionPrice"]objectAtIndex:indexPath.row]floatValue]; 
//  NSString *str1 = [NSString stringWithFormat:@"%.2f",a]; 
//  
     cell.lbl4.text = str; 

//// 
//  
    cell.img1.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[[_result_array valueForKey:@"artworkUrl60"]objectAtIndex:indexPath.row]]]]]; 
//  
//  
//  
//  
//  
//  
    return cell; 
} 
// 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [self performSegueWithIdentifier:@"segue" sender:self]; 

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

    cell.accessoryType = UITableViewCellAccessoryCheckmark; 



    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
} 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if ([[segue identifier] isEqualToString:@"segue"]) { 
     //Do something 

     NSIndexPath *index = [self.tableview indexPathForSelectedRow]; 


     SecondViewController *detailController = [segue destinationViewController]; 
     // detailController.txt2= [cricket objectAtIndex:index.row]; 



     detailController.imgg1= [UIImage imageNamed:[_result_array objectAtIndex:index.row]]; 



    } 

} 
@end 
관련 문제