alamofire objectmapper library 를 사용해서 파파고 번역 구현하기입니다.



//

//  PapagoDTO.swift

//  Papago

//

//  Created by stayfoolish on 2018. 9. 25..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit

import ObjectMapper


class PapagoDTO: Mappable {

    

    var message : Message?

    

    required init?(map: Map) {

        

    }

    

    func mapping(map: Map) {

        message <- map["message"]

    }

    

    class Message : Mappable{

        

        var result : Result?

        

        required init?(map: Map) {

            

        }

        

        func mapping(map: Map) {

            result <- map["result"]

        }

        class Result : Mappable{

            

            var translatedText : String?

            

            required init?(map: Map) {

                

            }

            

            func mapping(map: Map) {

                translatedText <- map["translatedText"]

            }

            

            

        }

        

        

    }


}


//

//  ViewController.swift

//  Papago

//

//  Created by stayfoolish on 2018. 9. 25..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit

import Alamofire

import AlamofireObjectMapper


class ViewController: UIViewController {


    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        

        var url = "https://openapi.naver.com/v1/papago/n2mt"

        var params = ["source":"ko",

                      "target":"en",

                      "text":"만나서 반갑습니다."]

        var header = ["Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",

                      "X-Naver-Client-Id":"Jx1o3o2eyOTv_odH_gNw",

                      "X-Naver-Client-Secret":"ewr_h8Gsgv"]

        

        Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: header).responseObject { (response:DataResponse<PapagoDTO>) in

            var papagoDTO = response.result.value

            print((papagoDTO?.message?.result?.translatedText)!)

        }

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }



}






import Swift


/*

- 스위프트 타입 캐스팅

 인스턴스의 타입을 확인하는 용도

 클래스의 인스턴스를 부모 혹은 자식 클래스의 타입으로 사용할 수 있는지 확인 용도

 is, as를 사용합니다.

 * 형변환은 'ex. let someDouble = Double(2)' 타입 캐스팅이 아니라 새로운 값을 생성하는 것입니다.

 

 */




// 예제 클래스


class Person {

    var name: String = ""

    func breath(){

        print("숨을 쉽니다")

    }

}


class Student: Person {

    var school: String = ""

    func goToSchool(){

        print("등교를 합니다")

    }

}


class UniversityStudent: Student{

    var major: String = ""

    func goToMT(){

        print("멤버쉽 트레이닝을 갑니다 신남!")

    }

}


// 인스턴스 생성


var myName: Person = Person()

var myName2: Student = Student()

var myName3: UniversityStudent = UniversityStudent()



// 타입확인


var result: Bool

result = myName is Person // true

result = myName is Student // false

result = myName is UniversityStudent // false


result = myName2 is Person // true

result = myName2 is Student  // true

result = myName2 is UniversityStudent // false


result = myName3 is Person // true

result = myName3 is Student // true

result = myName3 is UniversityStudent // true


if myName is UniversityStudent {

    print ("myName은 대학생입니다.")

}else if myName is Student {

    print("myName은 학생입니다")

}else if myName is Person {

    print("myName은 사람입니다")

} // myName은 사람입니다.


switch myName3 {

case is Person:

    print("myName3은 사람입니다")

case is Student:

    print("myName3은 학생입니다.")

case is UniversityStudent:

    print("myName3은 대학생입니다.")

default:

    print("myName은 사람도, 학생도, 대학생도 아닙니다.")

} // myName3은 사람입니다.





switch myName3 {

case is UniversityStudent:

    print("myName3은 대학생입니다")

case is Student:

    print("myName3은 학생입니다.")

case is Person:

    print("myName3은 사람입니다.")

default:

    print("myName은 사람도, 학생도, 대학생도 아닙니다.")

} // myName3은 대학생입니다.


/*

- 업 캐스팅 (Up Casting)

 as를 사용하여 부모클래스의 인스턴스로 사용할 수 있도록 컴파일러에게 타입정보를 전환해줍니다.

 Any혹은 AnyObject로도 타입정보를 변환할 수 있습니다.

 암시적으로 처리되므로 꼭 필요한 경우가 아니라면 생략해도 무방합니다.

 */


//UnversityStudent 인스턴스를 생성하며 Person 행세를 할 수 있도록 업 캐스팅

var mike: Person = UniversityStudent() as Person


var jenny: Student = Student()

// var jina: UniversityStudent = Person() as UniversityStudent // 컴파일 오류


// UniversityStudent 인스턴스를 생성하며 Any 행세를 할 수 있도록 업 캐스팅

var jina: Any = Person() // as Any 생략가능


/*

 - 다운 캐스팅(Down Casting)

 as? 또는 as!를 사용하여 자식 클래스의 인스턴스로 사용할 수 있도록 컴파일러에게 인스턴스의 타입정보를 전환해줍니다.

 

 A. 조건부 다운 캐스팅

 as? 를 사용합니다.

 캐스팅에 실패하면, 즉 캐스팅하려는 타입에 부합하지 않는 인스턴스라면 nil을 반환하기 때문에 결과의 타입은 옵셔널 타입입니다.

 */


var optionalCasted: Student?


optionalCasted = mike as? UniversityStudent

optionalCasted = jenny as? UniversityStudent // nil

optionalCasted = jina as? UniversityStudent // nil

optionalCasted = jina as? UniversityStudent // nil



/*

 B. 강제 다운 캐스팅

 as! 를 사용합니다.

 캐스팅에 실패하면, 즉 캐스팅하려는 타입에 부합하지 않는 인스턴스라면 런타임 오류가 발생합니다.

 캐스팅에 성공하면 옵셔널이 아닌 일반 타입을 반환합니다.

 */


var forcedCasted: Student


forcedCasted = mike as! UniversityStudent

//forcedCasted = jenny as! UniversityStudent // 런타임 오류

//forcedCasted = jina as! UniversityStudent // 런타임 오류

//forcedCasted = jina as! UniversityStudent // 런타임 오류


func doSomethingWithSwitch(someone: Person) {

    switch someone {

    case is UniversityStudent:

        (someone as! UniversityStudent).goToMT()

    case is Student:

        (someone as! Student).goToSchool()

    case is Person:

        (someone as! Person).breath()

    }

}


doSomethingWithSwitch(someone: mike as Person) // 멤버쉽 트레이닝을 갑니다 신남!

doSomethingWithSwitch(someone: mike) // 멤버쉽 트레이닝을 갑니다 신남!

doSomethingWithSwitch(someone: jenny) // 등교를 합니다

doSomethingWithSwitch(someone: myName) // 숨을 쉽니다


func doSomething(someone: Person) {

    if let universityStudent = someone as? UniversityStudent {

        universityStudent.goToMT()

    }else if let student = someone as? Student {

        student.goToSchool()

    }else if let person = someone as? Person {

        person.breath()

    }

}


doSomething(someone: mike as Person) // 멤버쉽 트레이닝을 갑니다 신남!

doSomething(someone: mike) // 멤버쉽 트레이닝을 갑니다 신남!

doSomething(someone: jenny) // 등교를 합니다

doSomething(someone: myName) // 숨을 쉽니다








//: Playground - noun: a place where people can play

import Swift



// 예제 클래스

// 사람 클래스

class Person {

    var name: String

    var job: String?

    var home: Apartment?

    

    init(name: String){

        self.name = name

    }

}


// 사람이 사는 집 클래스

class Apartment {

    var buildingNumber: String

    var roomNumber: String

    var `guard`: Person?

    var owner: Person?

    

    init(dong: String, ho:String){

        buildingNumber = dong

        roomNumber = ho

    }

}


// 옵셔널 체이닝 사용

let myName: Person? = Person(name: "myName")

let apart: Apartment? = Apartment(dong:"102", ho:"303")

let superman: Person? = Person(name: "superman")


// 옵셔널 체이닝이 실행 후 결과값이 nil일 수 있으므로 결과 타입도 옵셔널입니다.


// 만약 우리집의 경비원의 직업이 궁금하다면?


// 옵셔널 체이닝을 사용하지 않는다면...

func guardjob(owner: Person?){

    if let owner = owner {

        if let home = owner.home {

        if let `guard` = home.guard {

            if let guardJob = `guard`.job{

                print("우리집 경비원의 직업은 \(guardJob)입니다")

            }else {

                print("우리집 경비원은 직업이 없어요")

            }

        }

    }

  }

}

guardjob(owner:myName)


// 옵셔널 체이닝을 사용한다면

func guardJobWithOptionalChaining(owner:Person?){

    if let guardJob = owner?.home?.guard?.job{

        print("우리집 경비원의 직업은 \(guardJob)입니다")

    }else {

        print("우리집 경비원은 직업이 없어요")

    }

}




guardJobWithOptionalChaining(owner: myName)

// 우리집 경비원은 직업이 없어요


myName?.home?.guard?.job // nil


myName?.home = apart


myName?.home //Apratment


myName?.home?.guard //nil


// 경비원 할당


myName?.home?.guard = superman


myName?.home?.guard //Person


myName?.home?.guard?.name //superman


myName?.home?.guard?.job //nil


myName?.home?.guard?.job = "경비원"




/*

- nil 병합 연산자

중위 연산자입니다.??

optional ?? value

옵셔널 값이 nil일 경우, 우측의 값을 반환합니다.

띄어쓰기에 주의하여야 합니다.

 */


var guardJob: String


guardJob = myName?.home?.guard?.job ?? "슈퍼맨"

print(guardJob) // 경비원


myName?.home?.guard?.job = nil


guardJob = myName?.home?.guard?.job ?? "슈퍼맨"

print(guardJob) // 슈퍼맨










//

//  ViewController.swift

//  WeatherTable

//

//  Created by stayfoolish on 2018. 9. 21..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController,UITableViewDataSource {

    

    var datalist:[[String:String]] = [[:]]

    

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

        return datalist.count

    }

    

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        

        var dicTemp = datalist[indexPath.row]

        

        cell.textLabel?.text = dicTemp["지역"]

        

        let weatherStr = dicTemp["날씨"]

        

        cell.detailTextLabel?.text = weatherStr

        

        if weatherStr == "맑음"{

            cell.imageView?.image = UIImage(named: "sunny.png")

        }else if weatherStr == "비"{

            cell.imageView?.image = UIImage(named: "rainy.png")

        }else if weatherStr == "흐림"{

            cell.imageView?.image = UIImage(named: "cloudy.png")

        }else if weatherStr == "눈"{

            cell.imageView?.image = UIImage(named: "snow.png")

        }else {

            cell.imageView?.image = UIImage(named: "blizzard.png")

        }

        

        return cell

    }

    


    override func viewDidLoad() {

        super.viewDidLoad()

        let dict1 = ["지역":"한국","날씨":"비"]

        let dict2 = ["지역":"일본","날씨":"맑음"]

        let dict3 = ["지역":"중국","날씨":"눈"]

        let dict4 = ["지역":"스페인","날씨":"우박"]

        let dict5 = ["지역":"미국","날씨":"흐림"]

        let dict6 = ["지역":"영국","날씨":"비"]

        let dict7 = ["지역":"프랑스","날씨":"흐림"]

        let dict8 = ["지역":"브라질","날씨":"우박"]

        let dict9 = ["지역":"스위스","날씨":"맑음"]

        let dict10 = ["지역":"덴마크","날씨":"비"]

        let dict11 = ["지역":"스웨덴","날씨":"눈"]

        let dict12 = ["지역":"네덜란드","날씨":"비"]

        let dict13 = ["지역":"크로아티아","날씨":"맑음"]

        let dict14 = ["지역":"필리핀","날씨":"맑음"]

        let dict15 = ["지역":"독일","날씨":"눈"]

        let dict16 = ["지역":"헝가리","날씨":"비"]

        let dict17 = ["지역":"벨기에","날씨":"흐림"]

        let dict18 = ["지역":"핀란드","날씨":"우박"]

        let dict19 = ["지역":"이탈리아","날씨":"맑음"]

        

        datalist = [dict1,dict2,dict3,dict4,dict5,dict6,dict7,dict8,dict9,dict10,dict11,dict12,dict13,dict14,dict15,dict16,dict17,dict18,dict19]

        

        // Do any additional setup after loading the view, typically from a nib.

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }



}



















//

//  MainViewController.swift

//  ai 11

//

//  Created by stayfoolish on 2018. 9. 20..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit


class MainViewController: UIViewController , UITableViewDataSource, UITableViewDelegate {


    @IBOutlet weak var tableView: UITableView!

    

    let sampleData = SampleData()

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

        self.tableView.tableFooterView = UIView(frame: .zero)

        self.tableView.dataSource = self

        self.tableView.delegate = self

    }

    

    override func viewWillAppear(_ animated: Bool) {

        super.viewWillAppear(animated)

        

        self.navigationController?.navigationBar.prefersLargeTitles = true

    }

    

    override func viewWillDisappear(_ animated: Bool) {

        super.viewWillDisappear(animated)

        

        self.navigationController?.navigationBar.prefersLargeTitles = false

    }

    

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

        return self.sampleData.samples.count

    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "mainFeatureCell", for: indexPath) as! MainFeatureCell

        

        let sample = self.sampleData.samples[indexPath.row]

        

        cell.titleLabel.text = sample.title

        cell.descriptionLabel.text = sample.desription

        cell.featureImageView.image = UIImage(named: sample.image)

        

        return cell

    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)

        switch indexPath.row {

        case 0: self.performSegue(withIdentifier: "photoObjectDetection", sender: nil)

        case 1: self.performSegue(withIdentifier: "realTimeObjectDetection", sender: nil)

        case 2: self.performSegue(withIdentifier: "facialAnalysis", sender: nil)

        default:

            return

        }

    }



}





custom TableViewCell 커스텀 테이블뷰셀 만들기, 테이블뷰 줄 안보이게 하기 


//

//  MainFeatureCell.swift

//  ai 11

//

//  Created by stayfoolish on 2018. 9. 20..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit


class MainFeatureCell: UITableViewCell {


    @IBOutlet weak var featureImageView: UIImageView!

    @IBOutlet weak var titleLabel: UILabel!

    @IBOutlet weak var descriptionLabel: UILabel!

    

}


//

//  SampleData.swift

//  ai 11

//

//  Created by stayfoolish on 2018. 9. 20..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import Foundation


struct Sample {

    let title: String

    let desription: String

    let image: String

}


struct SampleData {

    let samples = [

        Sample(title: "Photo Object Detection", desription: "불러온 이미지에 있는 사물 인식", image: "ic_photo"),

        Sample(title: "Real Time Object Detection", desription: "실시간으로 카메라에 보이는 사물 인식", image: "ic_camera"),

        Sample(title: "Facial Analysis", desription: "사람 얼굴로부터 나이, 성별, 감정 추측", image: "ic_emotion")

    ]

}



//

//  MainViewController.swift

//  ai 11

//

//  Created by stayfoolish on 2018. 9. 20..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit


class MainViewController: UIViewController , UITableViewDataSource {


    @IBOutlet weak var tableView: UITableView!

    

    let sampleData = SampleData()

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

        self.tableView.tableFooterView = UIView(frame: .zero)

        self.tableView.dataSource = self

    }

    

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

        return self.sampleData.samples.count

    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "mainFeatureCell", for: indexPath) as! MainFeatureCell

        

        let sample = self.sampleData.samples[indexPath.row]

        

        cell.titleLabel.text = sample.title

        cell.descriptionLabel.text = sample.desription

        cell.featureImageView.image = UIImage(named: sample.image)

        

        return cell

    }

    



}




swift tableview 기본 data array 



//

//  MainViewController.swift

//  ai 11

//

//  Created by stayfoolish on 2018. 9. 20..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit


class MainViewController: UIViewController , UITableViewDataSource {


    @IBOutlet weak var tableView: UITableView!

    

    let dataArray = ["1","2","3","4","5","6","7","8","9","10",]

    

    

    override func viewDidLoad() {

        super.viewDidLoad()


        self.tableView.dataSource = self

    }

    

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

        return self.dataArray.count

    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "numberCell", for: indexPath)

        

        cell.textLabel?.text = self.dataArray[indexPath.row]

        

        return cell

    }

    



}



modal 방식



navigation controller 추가한 push 방식






//

//  FirstViewController.swift

//  ai 11

//

//  Created by stayfoolish on 2018. 9. 19..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit


class FirstViewController: UIViewController {


    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    

    @IBAction func buttonPressed(_ sender: UIButton) {

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

    }

    

    /*

    // 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.

    }

    */


}



//

//  SecondViewController.swift

//  ai 11

//

//  Created by stayfoolish on 2018. 9. 19..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import UIKit


class SecondViewController: UIViewController {


    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    

    @IBAction func goBack(_ sender: UIButton) {

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

    }

    

    /*

    // 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.

    }

    */


}






이번부터는 애플 개발자 계정이 필요하므로 나중에 개발자 계정을 만들게 되면 그 때부터 다시 만들어 보겠습니다.



메세지 보낸 시간 만들기


//

//  ChatModel.swift

//  FreeTalk

//

//  Created by stayfoolish on 2018. 9. 10..

//  Copyright © 2018년 stayfoolish. All rights reserved.

//


import ObjectMapper


class ChatModel: Mappable {

    

    

    

    @objc 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{

        @objc public var uid : String?

        @objc public var message : String?

        public var timestamp : Int?

        public required init?(map: Map) {

            

        }

        public  func mapping(map: Map) {

            uid <- map["uid"]

            message <- map["message"]

            timestamp <- map["timestamp"]

        }

    }

    

}




//

//  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

            


            if let time = self.comments[indexPath.row].timestamp{

                view.label_timestamp.text = time.toDayTime

            }

            

            

            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()

            

            if let time = self.comments[indexPath.row].timestamp{

                view.label_timestamp.text = time.toDayTime

            }

            

            

            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!,

                "timestamp" : ServerValue.timestamp()

            ]

            

            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.

     }

     */

    

}



extension Int{

    

    var toDayTime :String{

        let dateFormatter = DateFormatter()

        dateFormatter.locale = Locale(identifier: "ko_KR")

        dateFormatter.dateFormat = "yyyy.MM.dd HH:mm"

        let date = Date(timeIntervalSince1970: Double(self)/1000)

        return dateFormatter.string(from: date)

        

    }

    

}


/*

extension Int{

    var toDayTime :String{

        let dateFormatter = DateFormatter()

        dateFormatter.locale = Locale(identifier: "ko_KR")

        dateFormatter.dateFormat = "yyyy.MM.dd HH:mm"

        let date = Date(timeIntervalSince1970: Double(self)/1000)

        return dateFormatter.string(from: date)

    }

}

*/


class MyMessageCell: UITableViewCell{

    

    @IBOutlet weak var label_message: UILabel!

    @IBOutlet weak var label_timestamp: UILabel!

}


class DestinationMessageCell: UITableViewCell{

    

    @IBOutlet weak var imageview_profile: UIImageView!

    @IBOutlet weak var label_message: UILabel!

    @IBOutlet weak var label_name: UILabel!

    @IBOutlet weak var label_timestamp: UILabel!

}



+ Recent posts