Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Telegram extension example #6

Open
ricardopereira opened this issue Sep 20, 2018 · 1 comment
Open

Add Telegram extension example #6

ricardopereira opened this issue Sep 20, 2018 · 1 comment

Comments

@ricardopereira
Copy link
Member

ricardopereira commented Sep 20, 2018

Remote log using a Telegram group.

@ricardopereira
Copy link
Member Author

@objc class CriticalLogger: NSObject {

    private struct Payload: Codable {
        let chat: String
        let text: String

        private enum CodingKeys : String, CodingKey {
            case chat = "chat_id", text
        }
    }

    private static let token = <telegram_token>

    @objc class func remoteLog(_ text: String) {
        #if !DEBUG
        let payload = Payload(
            chat: "-484357798",
            text: text + " (v" + Bundle.main.appVersionDescription + ")"
        )

        let components = URLComponents(string: "https://api.telegram.org")
        guard let url = components?.url?.appendingPathComponent("bot\(token)").appendingPathComponent("sendMessage") else {
            print("No URL"); return
        }

        var request = URLRequest(url: url)
        do {
            request.httpBody = try JSONEncoder().encode(payload)
        }
        catch {
            print(error.localizedDescription)
        }
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data, let str = String(data: data, encoding: .utf8) {
                logEntry("Critical Logger data: \(str)", level: .verbose)
            }
            if let response = response {
                logEntry("Critical Logger response: \(response)", level: .verbose)
            }
            if let error = error {
                logError(error, title: "Critical Logger")
            }
        }
        task.resume()
        #endif
    }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant