2017-01-06 1 views
0

UISearchControllerを目的地に作成しています。ローカルストレージから連絡先を取り出してUITableViewに表示しています。値をインポートして表示することができます。私はユーザー名に基づいて値を探しています。私はNSArrayに検索した値を保存し、ユーザー名に従って検索した値を表示しています。ユーザー名を表示することができますが、私はcellForRowAtIndexPathを処理して、userthumbnailイメージとユーザーphonenumberのような特定のユーザーの詳細を表示できません。以下はUISearchControllerを使用しているときにUITableViewのcellForRowAtIndexPathを処理するときの問題

私は名前が適切な取得が、私は細部の残りの部分は誤解を検索するたびにcellForRowAtIndexPathで適切に処理されていないので、私のコード

@interface SelectContactViewController(){ 
    NSMutableArray *contactFullNameArr; 
     NSMutableArray *contactPhoneNumberArr; 
     NSMutableArray *contactImgPathArr; 

    NSArray *searchResultsArray;; 
} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

contactFullNameArr = [[NSMutableArray alloc]init]; 
    contactPhoneNumberArr = [[NSMutableArray alloc]init]; 
    contactImgPathArr = [[NSMutableArray alloc]init]; 

[self fetchContactsandAuthorization]; 

    searchResultsArray = [[NSArray alloc]init]; 

    self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil]; 
    self.searchController.searchBar.delegate = self; 
    self.searchController.searchResultsUpdater = self; 
    [self.searchController.searchBar sizeToFit]; 
    self.searchController.dimsBackgroundDuringPresentation = NO; 
    self.definesPresentationContext = YES; 
    _selectContactListTblView.tableHeaderView = self.searchController.searchBar; 

    [_selectContactListTblView reloadData]; 


} 


-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{ 
    NSString *searchString = self.searchController.searchBar.text; 
    NSPredicate *resultPredicate; 
     resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",searchString]; 
    searchResultsArray = [contactFullNameArr filteredArrayUsingPredicate:resultPredicate]; 
    [_selectContactListTblView reloadData]; 
} 

- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope{ 
    [self updateSearchResultsForSearchController:self.searchController]; 
} 



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *simpleTableIdentifier = @"SelectContactTableViewCell"; 

    SelectContactTableViewCell *cell = (SelectContactTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
    if (cell == nil) 
    { 
     NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SelectContactTableViewCell" owner:self options:nil]; 
     cell = [nib objectAtIndex:0]; 
    } 

    if(self.searchController.active){ 
       cell.contactFullName.text = [searchResultsArray objectAtIndex:indexPath.row]; 
//**************************i am confused here about setting the related user values to the cell************// 
      cell.contactProfileImage.image = [contactImgPathArr objectAtIndex:indexPath.row]; 

     cell.contactPhoneNumber.text = [contactPhoneNumberArr objectAtIndex:indexPath.row]; 
    } 
    else{ 
    cell.contactFullName.text = [contactFullNameArr objectAtIndex:indexPath.row]; 
    NSLog(@"img %@",[contactImgPathArr objectAtIndex:indexPath.row]); 
    cell.contactProfileImage.image = [contactImgPathArr objectAtIndex:indexPath.row]; 

    cell.contactPhoneNumber.text = [contactPhoneNumberArr objectAtIndex:indexPath.row]; 
    } 
    return cell; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return 80; 
} 

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

    if(self.searchController.active){ 
     return [searchResultsArray count]; 
    }else{ 
    return contactFullNameArr.count; 
    } 
} 

//for fetching contacts 
-(void)fetchContactsandAuthorization 
{ 
    // Request authorization to Contacts 
    CNContactStore *store = [[CNContactStore alloc] init]; 
    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) { 
     if (granted == YES) 
     { 
      //keys with fetching properties 
      NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey]; 
      NSString *containerId = store.defaultContainerIdentifier; 
      NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId]; 
      NSError *error; 
      NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error]; 

      NSLog(@"new %@",cnContacts); 

      if (error) 
      { 
       NSLog(@"error fetching contacts %@", error); 
      } 
      else 
      { 
       NSString *phone; 
       NSString *fullName; 
       NSString *firstName; 
       NSString *lastName; 
       UIImage *profileImage; 
       NSMutableArray *contactNumbersArray = [[NSMutableArray alloc]init]; 
       for (CNContact *contact in cnContacts) { 
        // copy data to my custom Contacts class. 
        firstName = contact.givenName; 
        lastName = contact.familyName; 

        if (lastName == nil) { 
         fullName=[NSString stringWithFormat:@"%@",firstName]; 
        }else if (firstName == nil){ 
         fullName=[NSString stringWithFormat:@"%@",lastName]; 
        } 
        else{ 
         fullName=[NSString stringWithFormat:@"%@ %@",firstName,lastName]; 
        } 
        UIImage *image = [UIImage imageWithData:contact.imageData]; 
        NSLog(@"imgold %@",image); 
        if (image != nil) { 
         profileImage = image; 
        }else{ 
         profileImage = [UIImage imageNamed:@"person-icon.png"]; 
        } 
        for (CNLabeledValue *label in contact.phoneNumbers) { 
         phone = [label.value stringValue]; 
         if ([phone length] > 0) { 
          [contactNumbersArray addObject:phone]; 
         } 
        } 


        [contactFullNameArr addObject:fullName]; 
        [contactPhoneNumberArr addObject:phone]; 
        [contactImgPathArr addObject:profileImage]; 
       } 
       dispatch_async(dispatch_get_main_queue(), ^{ 
        [_selectContactListTblView reloadData]; 
       }); 
      } 
     } 
    }]; 
} 

です。今私はケイトである第二のコンタクトを検索する場合enter image description here

リファレンス

ください。私はジョンのサムネイルとphonenumberをkateにマッピングしています。どんな助けでも本当に感謝します。

enter image description here

+1

、あなたは文句を言わないTj3n @アレイの一貫性のない – Tj3n

+0

に対処する必要があり、その後、すべての3名、電話や画像を保存するだけで1アレイに格納するオブジェクトを作成しますお返事ありがとうございます.3つの名前のオブジェクトを作成せずにこれを処理できませんか? – Madhu

+0

あなたがそれをしたくない場合は、各人物の名前、電話、画像を保持するオブジェクトを作成することを意味します。検索するときに同様の画像と電話を保持するために3 'searchResultsArray'を作成します。 – Tj3n

答えて

0
  1. NSObject subclasssを作成User.hに3つのプロパティを追加します
  2. Userと呼ばれる - のfullName、にphoneNumber、IMAGEPATH
  3. SelectContactViewControllerでは、各連絡先のUserオブジェクトを作成し、値を持つプロパティを移入。
  4. Userオブジェクトを配列NSArray *contactsに追加しました。
  5. 2番目の配列NSArray *filteredContactsを作成し、それをUITableView dataSourceとして使用します。次へ

更新updateSearchResultsForSearchController::私のプロジェクトの

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{ 
    NSString *searchString = self.searchController.searchBar.text; 
    NSPredicate *resultPredicate; 
     resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",searchString]; 
    self.filteredContacts = [self.contacts filteredArrayUsingPredicate:resultPredicate]; 
    [_selectContactListTblView reloadData]; 
} 
+0

オプションなしNSObjectサブクラスを作成して3つのプロパティを作成しましたが、imagePathプロパティをUIImageとして保持しました。上記のコードをチェックすると、私はcontact.imageDataからUIImageを直接格納しています。私はプロパティのいずれかでUIImageを使用しているため、アプリケーションはupdateSearchResultsForSearchControllerでクラッシュしています。すべてのプロパティは文字列でなければなりません。 ***キャッチされていない例外 'NSInvalidArgumentException'のためにアプリケーションを終了します、理由: 'コレクションでの/ contains演算子 @Armands L. – Madhu

+0

@MadhuあなたのUIimageをNSdata/stringフォーマット – rvx

0

一つは、これに類似していました。あなたの参照のためにこれをチェックしてください。

class StoreVariables: NSObject { 
var StoreList : NSMutableArray = NSMutableArray() 
var StoreMob : NSMutableArray = NSMutableArray() 
} 

私はクラス「StoreVariables」を作成しました。

var dataArray = StoreVariables() 
var filteredArray = StoreVariables() 
var shouldShowSearchResults = false 

通常のエントリの場合は「dataArray」、フィルタリングされたリストを保持する場合は「filteredArray」です。 searchBarの使用をチェックするための "shouldShowSearchResults"。

override func viewDidLoad() { 
    storeclass = StoreVariables() // initialize 
     searchbar.delegate = self 
    } 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    if shouldShowSearchResults { 
     return filteredArray.StoreList.count 
    } 
    else { 
     return storeclass.StoreList.count 
    } 

} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCellWithIdentifier("cell1") as! storeCell 

    cell.backgroundColor = UIColor.clearColor() 
    cell.selectionStyle = UITableViewCellSelectionStyle.None 
    if shouldShowSearchResults { 
     cell.storeName.text! = filteredArray.StoreList[indexPath.row] as! String 
     cell.storeMobile.text! = filteredArray.StoreMob[indexPath.row] as! String 
    } 
    else 
    { 
     cell.storeName.text! = storeclass.StoreList[indexPath.row] as! String 
     cell.storeMobile.text! = storeclass.StoreMob[indexPath.row] as! String 
     cell.delegate = self 
    } 
    } 

//検索バー代表

func searchBarCancelButtonClicked(searchBar: UISearchBar) { 
    shouldShowSearchResults = false 
    searchBar.text = "" 
    storeTableView.reloadData() 
    searchBar.resignFirstResponder() 
} 
func searchBarSearchButtonClicked(searchBar: UISearchBar) { 
    if !shouldShowSearchResults { 
     shouldShowSearchResults = true 
     updateSearchResultsForSearchController(searchBar) 
     storeTableView.reloadData() 
    } 

} 
func updateSearchResultsForSearchController(searchBar: UISearchBar) { 
    var searchString = searchbar.text 
    searchString = searchString!.uppercaseString 
    filteredArray.StoreList = [] 
    filteredArray.StoreMob = [] 
    if(storeclass.StoreList.count > 0) 
    { 
    for i in 0...storeclass.StoreList.count - 1{ 
     var mainString = storeclass.StoreList[i] 
     mainString = mainString.uppercaseString 
     let chk : Bool = (mainString.rangeOfString(searchString!, options: NSStringCompareOptions.CaseInsensitiveSearch).location) != NSNotFound 
     if (chk) 
     { 
      filteredArray.StoreList.addObject(storeclass.StoreList[i]) 
      filteredArray.StoreMob.addObject(storeclass.StoreMob[i]) 

     } 
     } 
    } 
} 
関連する問題