Search code examples
swiftsavetableviewxcode11saving-data

Saving data locally (IOS)


How would I be able to store data that is added into a tableView that I would be able to access and delete after the app is closed and loaded again?

My app basically has a contact section that you can add new contacts to the app, kinda like a offline version of instagram following. I want the user to be able to make a new contact on their device and for the new contact to be saved onto their device so that they and the app can access this information whenever they'd like.

I'd like to know how I can save the data once the table item is added to the table I have how I add data onto my tableView below.

How I add data onto my tableView:

     @IBAction func done(segue:UIStoryboardSegue) {
        let newContact = segue.source as! NewContactViewController
        FirstName = newContact.firstName
        LastName = newContact.lastName
           print("Adding the name: " + FirstName + " " + LastName + " to the nameArry")
        nameArry.append(FirstName + " " + LastName)
        print("Added " + nameArry[nameArry.count - 1] + " to name array")
        
        contacts.append(Contacts(MyContact: nameArry[nameArry.count - 1], Me: ""))
        
        let indexPath = IndexPath(row: myContact.count + contacts.count - 1, section: 0)
        
        tableView.beginUpdates()
        tableView.insertRows(at: [indexPath], with: .automatic)
        tableView.endUpdates()
        
        newContact.firstName = ""
        newContact.lastName = ""
        view.endEditing(true)
    }

How I load my table view:

extension ContactsViewController: UITableViewDataSource, UITableViewDelegate {
    
    
    
    // Get Number of items in table
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (myContact.count + contacts.count)
    }
    
    // Set custom hights for the diffrent rows
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.row == 0{
            return 60.0
            
        } else {
            return 35.0
        }
    }
    
    // Set the cells data
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        if indexPath.row < myContact.count {
            
            let myContactSchedule = myContact[indexPath.row]
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "MainUsersAccount") as!
            ContactsLayout
            
            cell.setMyContact(myContacts: myContactSchedule)
            return cell
            
        } else {
            
            let contactsSchedule = contacts[indexPath.row - myContact.count]
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "UserItem") as!
            ContactsLayout
            
            cell.setContacts(contacts: contactsSchedule)
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let result = UIView()
        
        // recreate insets from existing ones in the table view
        let insets = tableView.separatorInset
        let width = tableView.bounds.width - insets.left - insets.right
        let sepFrame = CGRect(x: insets.left, y: -0.5, width: width, height: 0.5)
        
        // create layer with separator, setting color
        let sep = CALayer()
        sep.frame = sepFrame
        sep.backgroundColor = tableView.separatorColor?.cgColor
        result.layer.addSublayer(sep)
        
        return result
    }
    
    // Deselect Row
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

This may be a fairly easy question to answer, but im new to making apps and can't seem to find an easy way to store this.

Thank you for your time, any help would be appreciated.


Solution

  • You have a number of options to save your app's data.

    Which storage option you choose, depends on a number of factors, such as a the volume of data plan to store, performance expectations, how complex your data structure is, Do you plan to sync the data across devices (For eg: Same user installs app on an iPhone & iPad), Security considerations etc.

    Bear in mind it's impossible to give an exhaustive list. Here are a few basic options.

    Storage Option 1 : Data that is stored locally on the device.

    • Use Userdefaults - quick and easy, but not recommended.
    • Store data in a file on the device. - Check out iOS Documents on serialisation.
    • Core Data - Use this, If you expect to have a large amount of data, with complex data structure.
    • Other databases, like SQLite. Check out FMDB.

    Storage Option 2 : If you plan to access the data from other locations, (another device, web app etc).

    • iCloud - Apple's cloud storage solution.
    • Firebase
    • Tons of other third party storage as a service options.