Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.8 kB
13
Indexable
Never
import Foundation
import UIKit

extension ParentChatController {
    var appDelegate : AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
}

class ParentChatController : MessagesViewController {
    
    @objc var messageId: String?
    @objc var messageTitle: String?
    var pageNumber = 0;
    var userMessageId = ""
    
    override func viewDidLoad() {
        userMessageId = messageId ?? ""
        let str_url = "API GOES HERE"
        sendRequest(str_url, parameters: ["message_id": MESSAGE_ID, "page_number": String(PAGE_NUMBER)]) { responseObject, error in
            guard let responseObject = responseObject, error == nil else {
                print(error ?? "Unknown error")
                return
            }
            
            print(responseObject.messages.count)
        }
    }
    
    
    func sendRequest(_ url: String, parameters: [String: String], completion: @escaping (ChatResponse?, Error?) -> Void) {
        var components = URLComponents(string: url)!
        components.queryItems = parameters.map { (key, value) in
            URLQueryItem(name: key, value: value)
        }
        var request = URLRequest(url: components.url!)
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let authValue = "Bearer \(String(describing: appDelegate.token!))"
        request.setValue(AUTH_VALUE, forHTTPHeaderField: "Authorization")
        print(request)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard
                let data = data,
                let response = response as? HTTPURLResponse,
                200 ..< 300 ~= response.statusCode,
                error == nil
            else {
                completion(nil, error)
                return
            }
            //let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [ChatResponse]
            let chatResponse = try? JSONDecoder().decode(ChatResponse.self, from: data)
            completion(chatResponse, nil)
        }
        task.resume()
    }
}

struct ChatResponse: Codable {
    let status: String
    let messages: [Message]
    let totalRows: Int

    enum CodingKeys: String, CodingKey {
        case status, messages
        case totalRows = "total_rows"
    }
}

// MARK: - Message
struct Message: Codable {
    let chatTime: String
    let createdAt: Int
    let senderName: String
    let receiverName: String
    let senderType: Int
    let message: String
    let id: Int

    enum CodingKeys: String, CodingKey {
        case chatTime = "chat_time"
        case createdAt = "created_at"
        case senderName = "sender_name"
        case receiverName = "receiver_name"
        case senderType = "sender_type"
        case message, id
    }
}
Leave a Comment