//
// ChatModel.swift
// FreeTalk
//
// Created by stayfoolish on 2018. 9. 10..
// Copyright © 2018년 stayfoolish. All rights reserved.
//
import ObjectMapper
class ChatModel: Mappable {
public var users :Dictionary<String,Bool> = [:] //채팅방에 참여한 사람들
public var comments :Dictionary<String,Comment> = [:] //채팅방의 대화내용
required init?(map: Map) {
}
func mapping(map: Map) {
users <- map["users"]
comments <- map["comments"]
}
public class Comment :Mappable{
public var uid : String?
public var message : String?
public required init?(map: Map) {
}
public func mapping(map: Map) {
uid <- map["uid"]
message <- map["message"]
}
}
}
//
// 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(UITableViewCell.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)
let imageview = UIImageView()
cell.addSubview(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 = UILabel()
cell.addSubview(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.
}
*/
}
//
// 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] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let view = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath)
view.textLabel?.text = self.comments[indexPath.row].message
return view
}
public var destinationUid :String? // 나중에 내가 채팅할 대상의 uid
override func viewDidLoad() {
super.viewDidLoad()
uid = Auth.auth().currentUser?.uid
sendButton.addTarget(self, action: #selector(createRoom), for: .touchUpInside)
checkChatRoom()
// Do any additional setup after loading the view.
}
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)
}
}
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.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()
})
}
/*
// 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.
}
*/
}
'Swift > firebase' 카테고리의 다른 글
스위프트 파이어베이스 카카오톡 #13 [ 말풍선 Chat Bubble2 만들기 ] swift firebase (0) | 2018.09.15 |
---|---|
스위프트 파이어베이스 카카오톡 #12 [ 말풍선 Chat Bubble 만들기 ] swift firebase (0) | 2018.09.14 |
스위프트 파이어베이스 카카오톡 #10 [ 메세지 보내기 ] swift firebase (0) | 2018.09.12 |
스위프트 파이어베이스 카카오톡 #9 [ 채팅방 데이터베이스 만들기 ] swift firebase (0) | 2018.09.11 |
스위프트 파이어베이스 카카오톡 #8 [ PeopleView2 만들기 ] swift firebase (0) | 2018.09.11 |