Я показываю фотографии всех пользователей и образование на странице, как мне просто удалить текущего пользователя из списка? - PullRequest
1 голос
/ 24 июня 2019

Поскольку текущий пользователь не заботится о своей информации, а только о других, он должен быть исключен из списка.Я читал, что для этого можно использовать выборку основных данных, но я не уверен, как и где включить NSFetchRequest.

Я пытаюсь использовать NSFetchRequest в разных местах, но я получаю, что методы класса могут быть объявлены только вошибки типа.

/// upstream

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


    return people.count

}

public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell

    let immy = cell.viewWithTag(1) as! UIImageView

    let person: Userx = people[indexPath.row]

    cell.lblName.text = person.Education

    if let PhotoPosts = person.PhotoPosts {
        let url = URL(string: PhotoPosts)
        immy.sd_setImage(with: url)
    }

    return cell
}

//// downstream

refArtists = Database.database().reference().child("people");

refArtists.observe(DataEventType.value,  with: {snapshot in

    if snapshot.childrenCount>0{

        self.people.removeAll()

        for people in snapshot.children.allObjects as! [DataSnapshot] {
            let peopleObject = people.value as? [String: AnyObject]
            let peopleEducation = peopleObject?["Education"] as? String
            let peoplePhotoPosts = peopleObject?["PhotoPosts"]  as? String
            let peopl = Userx(Education: peopleEducation, PhotoPosts: peoplePhotoPosts)
                self.people.append(peopl)

        }
        self.table.reloadData()
        print(snapshot)

    }

})

//// другой файл, который попадает в указанный выше файл

    let databaseRef = Database.database().reference()
    let uid = Auth.auth().currentUser!.uid
if Education.text == "" || {
    print ("missing")
    let alert = UIAlertController(title: "Error", message: "Missing Field.", preferredStyle: UIAlertControllerStyle.alert)
    let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
    alert.addAction(action)

            self.present(alert, animated: true, completion: nil)

}
else if takenImage == nil{

    let alert = UIAlertController(title: "Error", message: "Missing Photo.", preferredStyle: UIAlertControllerStyle.alert)
    let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
    alert.addAction(action)

    self.present(alert, animated: true, completion: nil)

}

else {

    databaseRef.child("people").child(uid).child("Education").setValue(self.Education.text!)

    self.performSegue(withIdentifier: "tohome", sender: nil)

}

Окончательным результатом будут все пользователи, кроме отображаемого текущего.

1 Ответ

1 голос
/ 24 июня 2019

ОП хотел бы прочитать всех пользователей, хранящихся в узле / people, но игнорировать эту информацию о пользователях.Предполагая, что используется Аутентификация Firebase и что каждый дочерний узел в узле / people имеет ключ этого пользовательского идентификатора.Структура будет

people
   uid_0 // firebase uid
      name: "Captain Oveur"
      email: "oveur@machogrande.com"
   uid_1
      name: "Mr. Unger"
      email: "unger@machogrande.com"
   uid_2
      name: "Mr. Dunn"
      email: "dunn@machogrande.com"

, и скажем, г-н Данн вошел в систему и является текущим пользователем.Следующий код читает всех пользователей в узле people и печатает их на консоли, но игнорирует информацию о прошедших проверку подлинности пользователей.

func fetchAllUsersExceptCurrentUser() {
    let thisUsersUid = Auth.auth().currentUser?.uid //Mr. Dunn's uid
    let usersRef = self.ref.child("users")
    usersRef.observeSingleEvent(of: .value, with: { snapshot in
        for user in snapshot.children.allObjects as! [DataSnapshot] {
            if user.key != thisUsersUid { //do not add this users info to the array
                let userObject = user.value as! [String: Any]
                let name = userObject["name"] as? String ?? "No name"
                let email = userObject["email"] as? String ?? "no email"
                print(name, email) //add the data to the array
            }
        }
    })
}

Обратите внимание, что self.ref является ссылкой на my Корневой узел Firebase.Вы бы заменили свой в.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...