0

I'm displaying user profiles as search results in another view controller so that on selecting a cell the user gets followed. I load the results from updateSearchResults method and it loads well but when I select the row to follow that user sometimes it throws an error, Fatal error: Index out of range.

my code :

func updateSearchResults(for searchController: UISearchController) {
    self.chooseResultsTableController.reloadData()
    let ref = Database.database().reference()
            let queryRef : DatabaseQuery
            let lastUser = self.resultsUsers.last

            guard searchController.searchBar.text != "" else {
                return
            }

            queryRef = ref.child("users").queryOrdered(byChild: "full Name").queryStarting(atValue: searchController.searchBar.text).queryEnding(atValue: searchController.searchBar.text!+"\u{f8ff}").queryLimited(toLast: 20)

            SVProgressHUD.show()
            var tempUsers2 = [user]()
            queryRef.observeSingleEvent(of: .value, with: { snapshot in

                for snap in snapshot.children {
                let userSnap = snap as! DataSnapshot
                let userKey = userSnap.key
                let userDict = userSnap.value as! [String:AnyObject]
                let aUser = user()

                    aUser.fullName = userDict["full Name"] as? String
                    let joinedSince = userDict["dateJoined"] as! Double
                    aUser.ImagePath = userDict["urlToImage"] as? String
                    aUser.about = userDict["about"] as? String
                    if let FollowingCount = userDict["followers"] as? [String : String] {
                        aUser.followers = FollowingCount.values.count
                    }

                    aUser.userId = userKey

                    let sensibleDate = joinedSince / 1000
                    let date = Date(timeIntervalSince1970: sensibleDate)
                    var finalString = String()
                    let secondsAgo = Int(Date().timeIntervalSince(date))
                    let minute = 60
                    let hour = 60 * minute
                    let day = 24 * hour
                    let week = 7 * day
                    if secondsAgo < minute {
        //                      finalString = "\(secondsAgo) Just now"
                        finalString = "Just now"
                    } else if secondsAgo < hour {
                        finalString = "\(secondsAgo / minute) minutes ago"
                    } else if secondsAgo < day {
                        finalString = "\(secondsAgo / hour) hours ago"
                    } else if secondsAgo < week {
                        finalString = "\(secondsAgo / day) days ago"
                    } else {
                        finalString = "\(secondsAgo / week) weeks ago"
                    }
                    aUser.joinedSince = finalString
                    aUser.untouchedDate = joinedSince

                        if userKey != lastUser?.userId {
                            tempUsers2.insert(aUser, at: 0)
                            print(tempUsers2)
    //                        self.users.removeAll()
                            print("\(self.resultsUsers.count) number of users")
                        }
                    }
                    SVProgressHUD.dismiss()
                    self.resultsUsers = tempUsers2
                    self.chooseResultsTableController.reloadData()
                })

}

Also, when I search with different keywords so that the table view data changes, the error seems to be guaranteed upon selection on the cell :(

the error code :

func checkFollowing(indexPath : IndexPath)  {

    let uid = Auth.auth().currentUser?.uid
    let ref = Database.database().reference()

    ref.child("users").child(uid!).child("following").queryOrderedByKey().observe(.value) { (snapshot) in
        if let following = snapshot.value as? [String : AnyObject] {
            for (_ , value) in following {
            if value as? String == self.resultsUsers[indexPath.row].userId {
                self.chooseResultsTableController.cellForRow(at: indexPath)?.accessoryType = .checkmark
            }

          }

        }

    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
mac
  • 17
  • 5
  • add the code where you get the error – Toto Mar 27 '20 at 10:26
  • @ Toto added the code where I'm getting the error – mac Mar 27 '20 at 10:37
  • you need o safety to unwrap your optionals to avoid the crash. Check this answer https://stackoverflow.com/questions/25195565/how-do-you-unwrap-swift-optionals – Toto Mar 27 '20 at 10:41
  • @ Toto I tried running after correcting the optionals but still, that error – mac Mar 27 '20 at 10:52
  • you get **Index out of range**, try checking first if the array has that index before accessing it. check **index < array.count** – Toto Mar 27 '20 at 10:54
  • @Toto It is not returning an index for some cases but still trying to figure out whyy – mac Mar 27 '20 at 11:12

1 Answers1

0

The error means that you try to access an array element not exists. for example, if your array size is 4, you try to access array[10]. I can't catch where exactly do you make it happens. But you should reload your tableview data anywhere you change its data source array size

Eyad Shokry
  • 151
  • 1
  • 9