Monday, November 9, 2026
HomeiOS Developmentios - I need my tableview row stay chosen after dismiss additionally

ios – I need my tableview row stay chosen after dismiss additionally

[ad_1]

I’m new to Swift and I do not understand how to do that. I’ve two view controllers. First one is ViewController in which there’s a label and choose contact button. Once I press choose contacts button it current AddContactVC there’s a desk view by which I fetched contacts identify, cellphone quantity and nation code from simulator system utilizing import contacts. I can even choose a number of row. After choosing a number of rows once I press Accomplished button. This AddContactVC will get dismissed and brings me again to the ViewController and all of the names of the contacts is available in label. Now downside is that this once I click on once more to pick Contact button the beforehand chosen cell ought to seem chosen. Under is my code of AddContactVC.

import UIKit
import ContactsUI

protocol phnContactDelegate:class {
    func continueClickDelegae(groupMamberArr : NSMutableArray)
}

var arrayall = NSMutableArray()

class AddContactVC: UIViewController, CNContactPickerDelegate {
    @IBOutlet weak var contactATbl: UITableView!
    @IBOutlet weak var blurView: UIView!
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var txtSearch: UITextField!
    @IBOutlet weak var btnCheck: UIButton!
    var objects = [CNContact]()
    var arrName: [String] = ["Haifa", "Ziad", "Aditya", "Robert", "Joseph"]
    var arrPhn: [String] = ["+919473515614", "+919473515614", "+919473515614", "+919473515614", "+919473515614"]
    var arrayList = [PhnDS]()
    var mainarrayList = [PhnDS]()
    var presenter: AddContactPresenterProtocol?
    var search = false
    var searchArray = [CNContact]()
    var mobNum: String = ""
    var mobNumName: String = ""
    var cuntryCode: String = ""
//    var arrayall = NSMutableArray()
    var mainAll = NSMutableArray()

    weak var delegate: phnContactDelegate?
    override func viewDidLoad() {
        tremendous.viewDidLoad()
        contactATbl.allowsMultipleSelection = true
        let retailer = CNContactStore()
        retrieveContactsWithStore(retailer: retailer)
        txtSearch.delegate = self
        // getContacts()
    }
    @IBAction func backClick(_ sender: Any) {
        if arrayall.depend != 0 {
            delegate?.continueClickDelegae(groupMamberArr: arrayall)
        }
        dismiss(animated: true, completion: nil)
    }
    
    func getContacts() {
        let retailer = CNContactStore()
        swap CNContactStore.authorizationStatus(for: .contacts){
        case .approved:
            retrieveContactsWithStore(retailer: retailer)

        // That is the tactic we'll create
        case .notDetermined:
            retailer.requestAccess(for: .contacts) { succeeded, err in
                guard err == nil && succeeded else{
                    return
                }
                self.retrieveContactsWithStore(retailer: retailer)

            }
        default:
            print("Not dealt with")
        }

    }
    func retrieveContactsWithStore(retailer: CNContactStore) {
     let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactEmailAddressesKey] as [Any]
        let request = CNContactFetchRequest(keysToFetch: keysToFetch as! [CNKeyDescriptor])
        var cnContacts = [CNContact]()
        do {
            attempt retailer.enumerateContacts(with: request) {
                (contact, cursor) -> Void in
                if (!contact.phoneNumbers.isEmpty) {
                }

                if contact.isKeyAvailable(CNContactImageDataKey) {
                    if let contactImageData = contact.imageData {
                        print(UIImage(information: contactImageData)) // Print the picture set on the contact
                    }
                } else {
                    // No Picture accessible

                }
                if (!contact.emailAddresses.isEmpty) {
                }
                cnContacts.append(contact)
                 self.objects = cnContacts
            }
        } catch let error {
            NSLog("Fetch contact error: (error)")
        }

        NSLog(">>>> Contact record:")
        for contact in cnContacts {
            let fullName = CNContactFormatter.string(from: contact, model: .fullName) ?? "No Title"
            NSLog("(fullName): (contact.phoneNumbers.description)")
        }
       self.contactATbl.reloadData()
        }
    
    func disableBlurEffect() {
        self.blurView.removeFromSuperview()
        self.navigationController?.popViewController(animated: true)

    }
    func getCountryCallingCode(countryRegionCode:String)->String{

            let prefixCodes = ["AF": "93", "AE": "971", "AL": "355", "AN": "599", "AS":"1", "AD": "376", "AO": "244", "AI": "1", "AG":"1", "AR": "54","AM": "374", "AW": "297", "AU":"61", "AT": "43","AZ": "994", "BS": "1", "BH":"973", "BF": "226","BI": "257", "BD": "880", "BB": "1", "BY": "375", "BE":"32","BZ": "501", "BJ": "229", "BM": "1", "BT":"975", "BA": "387", "BW": "267", "BR": "55", "BG": "359", "BO": "591", "BL": "590", "BN": "673", "CC": "61", "CD":"243","CI": "225", "KH":"855", "CM": "237", "CA": "1", "CV": "238", "KY":"345", "CF":"236", "CH": "41", "CL": "56", "CN":"86","CX": "61", "CO": "57", "KM": "269", "CG":"242", "CK": "682", "CR": "506", "CU":"53", "CY":"537","CZ": "420", "DE": "49", "DK": "45", "DJ":"253", "DM": "1", "DO": "1", "DZ": "213", "EC": "593", "EG":"20", "ER": "291", "EE":"372","ES": "34", "ET": "251", "FM": "691", "FK": "500", "FO": "298", "FJ": "679", "FI":"358", "FR": "33", "GB":"44", "GF": "594", "GA":"241", "GS": "500", "GM":"220", "GE":"995","GH":"233", "GI": "350", "GQ": "240", "GR": "30", "GG": "44", "GL": "299", "GD":"1", "GP": "590", "GU": "1", "GT": "502", "GN":"224","GW": "245", "GY": "595", "HT": "509", "HR": "385", "HN":"504", "HU": "36", "HK": "852", "IR": "98", "IM": "44", "IL": "972", "IO":"246", "IS": "354", "IN": "91", "ID":"62", "IQ":"964", "IE": "353","IT":"39", "JM":"1", "JP": "81", "JO": "962", "JE":"44", "KP": "850", "KR": "82","KZ":"77", "KE": "254", "KI": "686", "KW": "965", "KG":"996","KN":"1", "LC": "1", "LV": "371", "LB": "961", "LK":"94", "LS": "266", "LR":"231", "LI": "423", "LT": "370", "LU": "352", "LA": "856", "LY":"218", "MO": "853", "MK": "389", "MG":"261", "MW": "265", "MY": "60","MV": "960", "ML":"223", "MT": "356", "MH": "692", "MQ": "596", "MR":"222", "MU": "230", "MX": "52","MC": "377", "MN": "976", "ME": "382", "MP": "1", "MS": "1", "MA":"212", "MM": "95", "MF": "590", "MD":"373", "MZ": "258", "NA":"264", "NR":"674", "NP":"977", "NL": "31","NC": "687", "NZ":"64", "NI": "505", "NE": "227", "NG": "234", "NU":"683", "NF": "672", "NO": "47","OM": "968", "PK": "92", "PM": "508", "PW": "680", "PF": "689", "PA": "507", "PG":"675", "PY": "595", "PE": "51", "PH": "63", "PL":"48", "PN": "872","PT": "351", "PR": "1","PS": "970", "QA": "974", "RO":"40", "RE":"262", "RS": "381", "RU": "7", "RW": "250", "SM": "378", "SA":"966", "SN": "221", "SC": "248", "SL":"232","SG": "65", "SK": "421", "SI": "386", "SB":"677", "SH": "290", "SD": "249", "SR": "597","SZ": "268", "SE":"46", "SV": "503", "ST": "239","SO": "252", "SJ": "47", "SY":"963", "TW": "886", "TZ": "255", "TL": "670", "TD": "235", "TJ": "992", "TH": "66", "TG":"228", "TK": "690", "TO": "676", "TT": "1", "TN":"216","TR": "90", "TM": "993", "TC": "1", "TV":"688", "UG": "256", "UA": "380", "US": "1", "UY": "598","UZ": "998", "VA":"379", "VE":"58", "VN": "84", "VG": "1", "VI": "1","VC":"1", "VU":"678", "WS": "685", "WF": "681", "YE": "967", "YT": "262","ZA": "27" , "ZM": "260", "ZW":"263"]
            let countryDialingCode = prefixCodes[countryRegionCode]
            return countryDialingCode!

    }
   
}

extension AddContactVC: AddContactProtocol
{
    
}
extension AddContactVC : UITableViewDelegate, UITableViewDataSource
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection part: Int) -> Int {
       
        if search {
                        return searchArray.depend
                    } else {
                        return objects.depend
                    }
        
//        return self.objects.depend
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let indetifier =  "AddContactTableViewCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: indetifier, for: indexPath) as! AddContactTableViewCell
        cell.selectionStyle = .none
       
        
        if search {
            
            let contact = self.searchArray[indexPath.row]
           print("theis my contact arrau (self.searchArray)")
            let formatter = CNContactFormatter()
            
           
       
            
            
            cell.lblName.textual content = formatter.string(from: contact )
            if let actualNumber = contact.phoneNumbers.first?.worth as? CNPhoneNumber {
                //Get the label of the cellphone quantity

                //Strip out the stuff you do not want
                print(actualNumber.stringValue)
                cell.lblphnNumber.textual content = actualNumber.stringValue
            }
            }
        else
        {
        
        let contact = self.objects[indexPath.row]
       print("theis my contact arrau (self.objects)")
        let formatter = CNContactFormatter()
        
       
   
        
        
        cell.lblName.textual content = formatter.string(from: contact )
        if let actualNumber = contact.phoneNumbers.first?.worth as? CNPhoneNumber {
            //Get the label of the cellphone quantity

            //Strip out the stuff you do not want
            print(actualNumber.stringValue)
            cell.lblphnNumber.textual content = actualNumber.stringValue
        }
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
        let picture = UIImage(named: "check_ic")! as UIImage
            if let cell = contactATbl.cellForRow(at: indexPath) as? AddContactTableViewCell
        {
                
                cell.btnCheck.setBackgroundImage(picture, for: .regular)
                let contact : CNContact
                if search
                {
                     contact = self.searchArray[indexPath.row]
                }
                else
                {
                     contact = self.objects[indexPath.row]
                }
                    
                
                
               print("theis my contact arrau (self.objects)")
                let formatter = CNContactFormatter()
              
                
                if let actualNumber = contact.phoneNumbers.first?.worth as? CNPhoneNumber {
                    //Get the label of the cellphone quantity

                    //Strip out the stuff you do not want
                    print(actualNumber.stringValue)
                    self.mobNum = actualNumber.stringValue
                    let MccNamVar = actualNumber.worth(forKey: "countryCode") as? String
                    
//                    let MccNamVar = formatter.string(from: contact )
//
                    let countryCode = getCountryCallingCode(countryRegionCode: MccNamVar?.uppercased() ?? "")
                    //change nation area Settings>>Normal>>Language&Area>>Area
                    
                    let fullName: String = actualNumber.stringValue
                   
                    let string = fullName
                    if string.comprises(countryCode) {
                        let fullNameArr = fullName.elements(separatedBy: countryCode)


                        
                        let lastName: String = fullNameArr[1]

                        print("lastname", lastName)
                        self.mobNum = lastName
                    }
                    
                 
                    else  if string.prefix(1) == "0" {
                       
                        let fullNameArr = fullName.elements(separatedBy: string.prefix(1))
                        print("I discovered (string.prefix(0))") // I discovered He
                        let lastName: String = fullNameArr[1]

                        print("lastname", lastName)
                        self.mobNum = lastName
                    }

                    self.cuntryCode = countryCode
                  
                    self.mobNumName = contact.givenName
                    let phoneds  = PhnDS()
                    phoneds.country_code = self.cuntryCode
                    phoneds.phone_number = self.mobNum
                    phoneds.user_name = contact.givenName
                   
                    
                    self.arrayList.append(phoneds)

                    print("arrayList", self.arrayList.depend)
                    
                    for every in self.arrayList
                    {
                        let dict = NSMutableDictionary()
                        dict["country_code"] = every.country_code
                        dict["phone_number"] = every.phone_number.removeWhitespace()
                        dict["user_name"] = every.user_name

                        
                        let identify = every.user_name
                            if !arrayall.comprises(dict) {
                                arrayall.add(dict)

                            }


                        print("arrll", arrayall)
                        
                    }

                }
            }
    
    
    }
    
    
    
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let picture = UIImage(named: "uncheck_ic")! as UIImage
            if let cell = contactATbl.cellForRow(at: indexPath) as? AddContactTableViewCell
        {
                cell.btnCheck.setBackgroundImage(picture, for: .regular)
                let dict = NSMutableDictionary()

                for every in self.arrayList
                {
                    dict["country_code"] = every.country_code
                    dict["phone_number"] = every.phone_number
                    dict["user_name"] = every.user_name

                   
                    
                }
                
                     if arrayall.comprises(dict) {
                         print("dict have to delet", dict)
                         arrayall.take away(dict)

                     }


                 print("arrll", arrayall)
            }
    }
    
}
extension AddContactVC : UITextFieldDelegate
{
    func textField(_ textField: UITextField, shouldChangeCharactersIn vary: NSRange, replacementString string: String) -> Bool {
        let searchStr = txtSearch.textual content ?? ""
        
        searchArray = objects.filter {$0.givenName.lowercased().prefix(searchStr.depend) == searchStr.lowercased()}
               search = true
        print("SearchArray", searchArray)
                if(searchStr == "")
        {
            search = false}
        else
        {
            search = true
        }
        
        self.contactATbl.reloadData()
        return true
    }
    
    func textFieldDidChangeSelection(_ textField: UITextField) {
        let searchStr = txtSearch.textual content ?? ""
        if searchStr == "" {
            search = false}
        else {
            search = true
        }
        
        self.contactATbl.reloadData()
    }
    func textFieldDidEndEditing(_ textField: UITextField, purpose: UITextField.DidEndEditingReason) {

    }
}

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments