채팅화면 들어갔을 때 탭바 사라지는 것, 메세지가 화면에서 넘어갈 때 제일 아래 메세지로 화면 내려가는 것 수정, 키보드는 constraint 부분에서 못 찾아서 생략 다음에 찾아서 update 필요
//
// MainViewController.swift -> PeopleViewController.swift
// FreeTalk
//
// Created by stayfoolish on 2018. 9. 7..
// Copyright © 2018년 stayfoolish. All rights reserved.
//
import UIKit
import SnapKit
import Firebase
class PeopleViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var array : [UserModel] = []
var tableview : UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableview = UITableView()
tableview.delegate = self
tableview.dataSource = self
tableview.register(PeopleViewTableCell.self, forCellReuseIdentifier: "Cell")
view.addSubview(tableview)
tableview.snp.makeConstraints { (m) in
m.top.equalTo(view)
m.bottom.left.right.equalTo(view)
}
Database.database().reference().child("users").observe(DataEventType.value, with: { (snapshot) in
self.array.removeAll()
let myUid = Auth.auth().currentUser?.uid
for child in snapshot.children {
let fchild = child as! DataSnapshot
let userModel = UserModel()
userModel.setValuesForKeys(fchild.value as! [String : Any])
if(userModel.uid == myUid){
continue
}
self.array.append(userModel)
}
DispatchQueue.main.async {
self.tableview.reloadData();
}
})
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "Cell", for :indexPath) as! PeopleViewTableCell
let imageview = cell.imageview!
imageview.snp.makeConstraints{(m) in
m.centerY.equalTo(cell)
m.left.equalTo(cell).offset(10)
m.height.width.equalTo(50)
}
URLSession.shared.dataTask(with: URL(string: array[indexPath.row].profileImageUrl!)!) { (data, response, err) in
DispatchQueue.main.async {
imageview.image = UIImage(data: data!)
imageview.layer.cornerRadius = imageview.frame.size.width/2
imageview.clipsToBounds = true
}
}.resume()
let label = cell.label!
label.snp.makeConstraints{ (m) in
m.centerY.equalTo(cell)
m.left.equalTo(imageview.snp.right).offset(20)
}
label.text = array[indexPath.row].userName
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let view = self.storyboard?.instantiateViewController(withIdentifier: "ChatViewController") as? ChatViewController
view?.destinationUid = self.array[indexPath.row].uid
self.navigationController?.pushViewController(view!, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
class PeopleViewTableCell: UITableViewCell{
var imageview: UIImageView! = UIImageView()
var label: UILabel! = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?){
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.addSubview(imageview)
self.addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//
// ChatViewController.swift
// FreeTalk
//
// Created by stayfoolish on 2018. 9. 10..
// Copyright © 2018년 stayfoolish. All rights reserved.
//
import UIKit
import Firebase
class ChatViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableview: UITableView!
@IBOutlet weak var textfield_message: UITextField!
@IBOutlet weak var sendButton: UIButton!
var uid : String?
var chatRoomUid : String?
var comments : [ChatModel.Comment] = []
var userModel :UserModel?
override func viewDidLoad() {
super.viewDidLoad()
uid = Auth.auth().currentUser?.uid
sendButton.addTarget(self, action: #selector(createRoom), for: .touchUpInside)
checkChatRoom()
self.tabBarController?.tabBar.isHidden = true
// Do any additional setup after loading the view.
}
//종료
override func viewWillDisappear(_ animated: Bool) {
self.tabBarController?.tabBar.isHidden = false
}
func keyboardWillShow(notification : Notification){
UIView.animate(withDuration: 0 , animations: {
self.view.layoutIfNeeded()
}, completion: {
(complete) in
if self.comments.count > 0 {
self.tableview.scrollToRow(at: IndexPath(item: self.comments.count - 1 , section: 0), at: UITableViewScrollPosition.bottom, animated: true)
}
})
}
/*
if let keyboardSize = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue{
self.bottomContraint.constant = keyboardSize.height
}
func keyboardWillHide(notification: Notification){
self.bottomContraint.constant = 20
self.view.layoutIfNeeded()
}
*/
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(self.comments[indexPath.row].uid == uid){
let view = tableView.dequeueReusableCell(withIdentifier: "MyMessageCell", for: indexPath) as! MyMessageCell
view.label_message.text = self.comments[indexPath.row].message
view.label_message.numberOfLines = 0
return view
}else{
let view = tableView.dequeueReusableCell(withIdentifier: "DestinationMessageCell", for: indexPath) as! DestinationMessageCell
view.label_name.text = userModel?.userName
view.label_message.text = self.comments[indexPath.row].message
view.label_message.numberOfLines = 0;
let url = URL(string:(self.userModel?.profileImageUrl)!)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, err) in
DispatchQueue.main.async {
view.imageview_profile.image = UIImage(data: data!)
view.imageview_profile.layer.cornerRadius = view.imageview_profile.frame.width/2
view.imageview_profile.clipsToBounds = true
}
}).resume()
return view
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
public var destinationUid :String? // 나중에 내가 채팅할 대상의 uid
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func createRoom(){
let createRoomInfo : Dictionary<String,Any> = [ "users" : [
uid!: true,
destinationUid! :true
]
]
if(chatRoomUid == nil){
self.sendButton.isEnabled = false
// 방 생성 코드
Database.database().reference().child("chatrooms").childByAutoId().setValue(createRoomInfo, withCompletionBlock: { (err, ref) in
if(err == nil){
self.checkChatRoom()
}
})
}else{
let value :Dictionary<String,Any> = [
"uid" : uid!,
"message" : textfield_message.text!
]
Database.database().reference().child("chatrooms").child(chatRoomUid!).child("comments").childByAutoId().setValue(value, withCompletionBlock: { (err, ref) in
self.textfield_message.text = ""
})
}
}
func checkChatRoom(){
Database.database().reference().child("chatrooms").queryOrdered(byChild: "users/"+uid!).queryEqual(toValue: true).observeSingleEvent(of: DataEventType.value,with: { (datasnapshot) in
for item in datasnapshot.children.allObjects as! [DataSnapshot]{
if let chatRoomdic = item.value as? [String:AnyObject]{
let chatModel = ChatModel(JSON: chatRoomdic)
if(chatModel?.users[self.destinationUid!] == true){
self.chatRoomUid = item.key
self.sendButton.isEnabled = true
self.getDestinationInfo()
}
}
}
})
}
func getDestinationInfo(){
Database.database().reference().child("users").child(self.destinationUid!).observeSingleEvent(of: DataEventType.value, with: { (datasnapshot) in
self.userModel = UserModel()
self.userModel?.setValuesForKeys(datasnapshot.value as! [String:Any])
self.getMessageList()
})
}
func getMessageList(){
Database.database().reference().child("chatrooms").child(self.chatRoomUid!).child("comments").observe(DataEventType.value, with: { (datasnapshot) in
self.comments.removeAll()
for item in datasnapshot.children.allObjects as! [DataSnapshot]{
let comment = ChatModel.Comment(JSON: item.value as! [String:AnyObject])
self.comments.append(comment!)
}
self.tableview.reloadData()
if self.comments.count > 0{
self.tableview.scrollToRow(at: IndexPath(item:self.comments.count - 1,section:0), at: UITableViewScrollPosition.bottom, animated: true)
}
})
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
class MyMessageCell: UITableViewCell{
@IBOutlet weak var label_message: UILabel!
}
class DestinationMessageCell: UITableViewCell{
@IBOutlet weak var imageview_profile: UIImageView!
@IBOutlet weak var label_message: UILabel!
@IBOutlet weak var label_name: UILabel!
}
'Swift > firebase' 카테고리의 다른 글
스위프트 파이어베이스 카카오톡 #15 [ 대화방 리스트(Chat Room List - 2) 만들기 ] swift firebase (0) | 2018.09.17 |
---|---|
스위프트 파이어베이스 카카오톡 #14 [ 대화방 리스트(Chat Room List) 만들기 ] swift firebase (0) | 2018.09.16 |
스위프트 파이어베이스 카카오톡 #12 [ 말풍선 Chat Bubble 만들기 ] swift firebase (0) | 2018.09.14 |
스위프트 파이어베이스 카카오톡 #11 [ 메세지 나타내기 ] swift firebase (0) | 2018.09.13 |
스위프트 파이어베이스 카카오톡 #10 [ 메세지 보내기 ] swift firebase (0) | 2018.09.12 |