0

I have a TabBar Application and I'm trying to set up a favorites tab. I have managed to create a button and to send the favorited cell to the tab but right now if i add to favorites they are added correctly into the favorites tab but if i quit the app it doesn't save the favorites . How can i save the favorited cells in the favorite tab? would UserDefault do the best job? and if so how can it be done...

This is how i set up my favorite button :

//create a new button
        let Favoritebutton: UIButton = UIButton(type: UIButtonType.custom)
        //set image for button
        Favoritebutton.setImage(UIImage(named: "EmptyHeart.png"), for: .normal)
        Favoritebutton.setImage(UIImage(named: "FilledHeart.png"), for: .selected)
        //add function for button
        Favoritebutton.addTarget(self, action: #selector(self.button), for: .touchUpInside)
        //set frame
        Favoritebutton.frame = CGRect(x:0,y: 0,width: 35,height: 35)
        
        Favoritebutton.isSelected = UserDefaults.standard.bool(forKey: "isSaved")
        
        let barButton = UIBarButtonItem(customView: Favoritebutton)
        //assign button to navigationbar
        
        self.navigationItem.rightBarButtonItem = barButton
        
    }


    @IBAction func button(sender: UIButton) {
        let newValue = !sender.isSelected
        sender.isSelected = newValue
        UserDefaults.standard.set(newValue, forKey: "isSaved")
        
        let tabItem = self.tabBarController?.tabBar.items![3]
        sel_val = tabItem?.badgeValue
        if(sel_val == nil){
            sel_val = "0"
        }
        let sel_num  = Int(sel_val!)
        
        let fav: NSMutableArray = []
        fav.add(barImage)
        fav.add(barName)
        fav.add(streetName)
        if sender.isSelected {
            tabItem!.badgeValue = String(format: "%d", sel_num! + 1)
            favorite.add(fav)
        } else {
            tabItem!.badgeValue = String(format: "%d", sel_num! - 1)
            favorite.remove(fav)
        }
    }
Community
  • 1
  • 1
Newbie Questions
  • 463
  • 1
  • 11
  • 31

1 Answers1

0

@Newbie - I think you are not checking, second time when app open what is your favourite tab with your NSUserDefault.

Hari c
  • 1,139
  • 11
  • 11
  • Probably not ... How can i do that? – Newbie Questions Apr 16 '17 at 11:54
  • When you open app, You can check is there any favourite item is selected or not, if selected you can identify which is selected based on that you can show – Hari c Apr 16 '17 at 12:03
  • Yes sure, But i am not much aware about swift.I will explain the flow you can go through. - When app open in launch option you can check is there any selected item then fallow this *URL*( http://stackoverflow.com/questions/2325780/how-to-set-the-tab-bar-item-1-to-be-selected-by-default-in-iphone) – Hari c Apr 16 '17 at 12:08