//問題解決 我發現了這件事由我自己,對你的幫助還是感謝:=)Swift3 /火力地堡更新孩子
我嘗試建立一個類似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)
向下跌破我的火力地堡結構看起來像
這是我的結構看起來像
我想1的值,每次更新的FUNC「addComment」票號的用戶評論
This is my JSON Tree in written format
您已經包含在你的問題的JSON樹的照片的完成者。請用實際的JSON替換爲文本,您可以通過點擊Firebase數據庫控制檯中的導出按鈕輕鬆獲取。將JSON作爲文本可以搜索,使我們能夠輕鬆使用它來測試您的實際數據,並將其用於我們的答案中,並且通常只是一件好事。 –
https://witzeapp-4ec48.firebaseio.com/是你的意思嗎? :哦,對不起,我是一個絕對的初學者。 –
OKAy我已經用書面格式的JSON樹的圖片更新了它。希望有所幫助。 –