gpt4 book ai didi

ios - Swift3/Firebase 更新子项

转载 作者:行者123 更新时间:2023-11-30 12:52:45 28 4
gpt4 key购买 nike

//问题已解决我自己发现了它,仍然感谢您的帮助:=)

我尝试构建一个类似 Instagram 的应用程序用于学习目的。我可以从 Firebase 上传和检索数据。当我上传新图片时,我将评论值设置为0。因此,当用户发表评论时,我想更新子项(“kommentAnzahl”)的值+1表示新评论,负-1表示删除的评论(删除还不重要)。这样我就可以让我的标签 anzahlKommentare 在每个帖子下方显示用户的评论数量(就像 Instagram 一样)

我的完整代码在下面

class MemesTableViewController: UITableViewController {

var kommentarArray = [FotoComment]()
var dataBaseRef : FIRDatabaseReference!
var storageRef : FIRStorageReference!
var posts = [PostMitBild]()
var segmentedControl : HMSegmentedControl!

override func viewDidLoad() {
super.viewDidLoad()

segmentedControl = HMSegmentedControl(sectionTitles: ["Top Heute", "Beliebteste", "Neue"])
segmentedControl.frame = CGRect(x: 10, y: 10, width: 300, height: 60)
segmentedControl.backgroundColor = UIColor.red
segmentedControl.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
segmentedControl.borderColor = UIColor.brown
segmentedControl.tintColor = UIColor.black
segmentedControl.selectionIndicatorColor = UIColor.gray


segmentedControl.addTarget(self, action: #selector(getter: MemesTableViewController.segmentedControl), for: UIControlEvents.valueChanged)
tableView.tableHeaderView = segmentedControl

segmentedAction()
}

func segmentedAction() {
if segmentedControl.selectedSegmentIndex == 0 {

let postRef = FIRDatabase.database().reference().child("MemesBilder")

postRef.observe(.value, with: { (snapshot) in
var newPost = [PostMitBild]()
for post in snapshot.children {

let Post = PostMitBild(snapshot: post as! FIRDataSnapshot)
newPost.insert(Post, at: 0)

}

self.posts = newPost
DispatchQueue.main.async {

self.tableView.reloadData()


}

}, withCancel: { (error) in
print(error.localizedDescription)
})

}

}

//------------------------------------------

override func viewWillAppear(_ animated: Bool) {

if FIRAuth.auth()?.currentUser == nil {

let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Login")
self.present(vc, animated: true, completion: nil)

}

}

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

if let seconds = posts[indexPath.row].postDate {
let timestamp = NSDate(timeIntervalSince1970: seconds)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm"
cell.uploadDatum.text = dateFormatter.string(from: timestamp as Date)

}

cell.kommentarZähler.text = String(posts[indexPath.row].kommentarAnzahl)
cell.usernameTextField.text = posts[indexPath.row].username
cell.postContent.text = posts[indexPath.row].content


storageRef = FIRStorage.storage().reference(forURL: posts[indexPath.row].userImageUrlString)
storageRef.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in
if error == nil {
DispatchQueue.main.async {
if let data = data {
cell.UserImageView.image = UIImage (data: data)
}
}

}else {
print(error?.localizedDescription)
}
})

let storageRef2 = FIRStorage.storage().reference(forURL: posts[indexPath.row].PostImageUrlString)
storageRef2.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in
if error == nil {
DispatchQueue.main.async {
if let data = data {

cell.postImageView.image = UIImage (data: data)
}

}
}else {
print(error?.localizedDescription)
}
})

return cell

}

//done!!!! ------------------------------------------

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
tableView.deleteRows(at: [indexPath], with: .fade)


let ref = posts[indexPath.row].ref
ref!.removeValue()

posts.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)

}
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var numberOfRows = 0
switch segmentedControl.selectedSegmentIndex {
case 0 : numberOfRows = posts.count

case 1: numberOfRows = posts.count

default: break


}

return numberOfRows
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 420.00
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segmentedControl.selectedSegmentIndex == 0 {
if segue.identifier == "addComment" {
let vc = segue.destination as! CommentTableViewController
let indexPath = tableView.indexPathForSelectedRow!

vc.selectedPosts = posts[indexPath.row]
}

}
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if segmentedControl.selectedSegmentIndex == 0 {
performSegue(withIdentifier: "addComment", sender: self)
}
if segmentedControl.selectedSegmentIndex == 1 {
performSegue(withIdentifier: "addComment", sender: self)
}
if segmentedControl.selectedSegmentIndex == 2 {
performSegue(withIdentifier: "addComment", sender: self)
}
}

}



import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage

class CommentTableViewController: UITableViewController {

@IBOutlet weak var komentarZähler: UILabel!
@IBOutlet weak var UserImageView: UIImageView!
@IBOutlet weak var usernameTextField: UILabel!
@IBOutlet weak var postImageView: UIImageView!
@IBOutlet weak var postContent: UITextView!

var dataBaseRef : FIRDatabaseReference!
var storageRef : FIRStorageReference!
var commentsArray = [FotoComment]()
var selectedPosts:PostMitBild!
var DataBaseRef : FIRDatabaseReference! {
return FIRDatabase.database().reference()
}

override func viewDidLoad() {
super.viewDidLoad()
configurePost()

let commentRef = selectedPosts.ref!.child("Kommentare")

commentRef.observe(.value, with: { (snapshot) in
var newComments = [FotoComment]()
for item in snapshot.children {
let neuerKommentar = FotoComment(snapshot: item as! FIRDataSnapshot)
newComments.insert(neuerKommentar, at: 0)

}
self.commentsArray = newComments
self.tableView.reloadData()

}, withCancel: { (error) in
print(error.localizedDescription)
})

}
@IBAction func addComment(_ sender: UIBarButtonItem) {

let alertView = UIAlertController(title: "Kommentar", message: "Füge einen Kommentar hinzu", preferredStyle: UIAlertControllerStyle.alert)
alertView.addTextField { (textfield) in
textfield.placeholder = "Einen neuen Kommentar hinzufügen"

}

let sendCommentAction = UIAlertAction(title: "Kommentieren", style: .default) { (action) in
let textfield = alertView.textFields!.first!

let comment = FotoComment(content: textfield.text! , postId: self.selectedPosts.postId , username: (FIRAuth.auth()!.currentUser!.displayName!) , userImageUrlString: String(describing: FIRAuth.auth()!.currentUser!.photoURL!), postDate: (NSDate().timeIntervalSince1970))

let commentRef = self.selectedPosts.ref!.child("Kommentare").childByAutoId()

let myReference = FIRDatabase.database().reference()
myReference.child("MemesBilder").child("kommentarAnzahl").setValue(["kommentarAnzahl": 1])

commentRef.setValue(comment.toAnyObject())

// commentRef.child("kommentarAnzahl").updateChildValues(["kommentarAnzahl" : 1])

}

let cancelAction = UIAlertAction(title: "Abbrechen", style: .cancel, handler: nil)
alertView.addAction(sendCommentAction)
alertView.addAction(cancelAction)
self.present(alertView, animated: true, completion: nil)

}

// 2----------------------------------------------

func configurePost() {

usernameTextField.text = selectedPosts.username
postContent.text = selectedPosts.content


storageRef = FIRStorage.storage().reference(forURL: selectedPosts.userImageUrlString)
storageRef.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in
if error == nil {
DispatchQueue.main.async {
if let data = data {
self.UserImageView.image = UIImage (data: data)
}
}

}else {
print(error?.localizedDescription)
}
})
let storageRef2 = FIRStorage.storage().reference(forURL: selectedPosts.PostImageUrlString)
storageRef2.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in
if error == nil {
DispatchQueue.main.async {
if let data = data {

self.postImageView.image = UIImage (data: data)
}

}
}else {
print(error?.localizedDescription)
}
})

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
komentarZähler.text = "Kommentare: \(commentsArray.count)"

return commentsArray.count

}

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

if let seconds = commentsArray[indexPath.row].postDate {
let timestamp = NSDate(timeIntervalSince1970: seconds)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ss"
cell.uploadDatum.text = dateFormatter.string(from: timestamp as Date)

}

cell.usernameTextField.text = commentsArray[indexPath.row].username
cell.postContent.text = commentsArray[indexPath.row].content

storageRef = FIRStorage.storage().reference(forURL: commentsArray[indexPath.row].userImageUrlString!)
storageRef.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in
if error == nil {
DispatchQueue.main.async {
if let data = data {
cell.UserImageView.image = UIImage (data: data)
}
self.tableView.reloadData()
}


}else {
print(error?.localizedDescription)
}

})
return cell
}

}

import UIKit
import Firebase
import FirebaseStorage
import FirebaseAuth
import FirebaseDatabase

class AddImageViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIPickerViewDelegate {

@IBOutlet weak var postImage: UIImageView!

@IBOutlet weak var textView: UITextView!

var dataBaseRef : FIRDatabaseReference! {
return FIRDatabase.database().reference()
}

var storageRef : FIRStorageReference! {
return FIRStorage.storage().reference()
}

override func viewDidLoad() {
super.viewDidLoad()

}

@IBAction func chooseImage(_ sender: UIButton) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.allowsEditing = true

let alertController = UIAlertController(title: "Bild aussuchen", message: "Suche dir dein neues Profilbild aus", preferredStyle: .actionSheet)

let cameraAction = UIAlertAction(title: "Kamera", style: .default, handler: { (action) in
pickerController.sourceType = .camera
self.present(pickerController, animated: true, completion: nil)
})
let photoLibraryAction = UIAlertAction(title: "Fotoalbum", style: .default, handler: { (action) in
pickerController.sourceType = .photoLibrary
self.present(pickerController, animated: true, completion: nil)

})
let safedPhotoAction = UIAlertAction(title: "Fotos", style: .default, handler: { (action) in
pickerController.sourceType = .savedPhotosAlbum
self.present(pickerController, animated: true, completion: nil)

})

let cancelAction = UIAlertAction(title: "Abbrechen", style: .destructive, handler: nil)
alertController.addAction(cameraAction)
alertController.addAction(photoLibraryAction)
alertController.addAction(safedPhotoAction)
alertController.addAction(cancelAction)

present(alertController, animated: true, completion: nil)

}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
self.postImage.image = image

self.dismiss(animated: true, completion: nil)
}

@IBAction func SafeAction(_ sender: UIBarButtonItem) {
let data = UIImageJPEGRepresentation(self.postImage.image!, 0.5)
let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpeg"
let postId = "\(FIRAuth.auth()!.currentUser!.uid)\(NSUUID().uuidString)"
let imagePath = "postIMAGES\(postId)/postPic.jpg"

storageRef.child(imagePath).put(data!, metadata: metadata) { (metadata, error) in
if error == nil {

let postRef = self.dataBaseRef.child("MemesBilder").childByAutoId()
let post = PostMitBild(content: self.textView.text!, postId: postId, username: (FIRAuth.auth()?.currentUser?.displayName!)!, PostImageUrlString: String(describing: metadata!.downloadURL()!), userImageUrlString: String(describing: FIRAuth.auth()!.currentUser!.photoURL!), postDate: (NSDate().timeIntervalSince1970), kommentarAnzahl: 0)

postRef.setValue(post.toAnyObject())


let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Memes")
self.present(vc, animated: true, completion: nil)


}else {
print(error!.localizedDescription)
}
}
_ = navigationController?.popToRootViewController(animated: true)
}

}

这些是我的 3 个 VC,用于显示图片 (MemesTableView)、用于添加图片 (AddImageView) 和用于评论上传的图片 (CommentTableView)

下面是我的 Firebase 结构的样子

这就是我的结构的样子 this is what my struct looks like

我想在每次用户评论时将函数“addComment”中的投票数更新为 1

This is my JSON Tree in written format

最佳答案

  • 我给出了一个用于更新 firebase 中投票计数值的示例函数。尝试以下方法

    func adddComment() {
    dataBaseRef.child("MemesBilder").child(userId).child("anzahlKommentare").runTransactionBlock({ (currentData: FIRMutableData) -> FIRTransactionResult in
    var voteCount = currentData.value as? Double
    if (voteCount == nil) {
    voteCount = 0
    }
    currentData.value = voteCount! + 1
    return FIRTransactionResult.successWithValue(currentData)
    })
    }

关于ios - Swift3/Firebase 更新子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40753529/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com