Sending Message Error To Webhook Slack

From IOS App to Slack

Photo by Grace To on Unsplash

This time i will report app error to slack using webhook. A webhook in web development is a method of augmenting or altering the behavior of a web page or web application with custom callbacks.
The first thing to do is register your app to slack and following this link https://api.slack.com/

Register Webhook in Slack

Author

After create app next step is select Incomming webhooks and tap Add New Webhook to Workspace you can select channel in your slack what you want and tap Allow

Author

Now copy Webhook URL and paste in your app, for template in slack check this link https://app.slack.com/block-kit-builder, this example my template
with JSON data in Build Kit Builder select Attachment Preview .

{
"attachments": [
{
"color": "#f2c744",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*username:* \n Fred \n *error_code:* \n 500 \n *line_code:* \n 100 \n *function:* \n getHelp \n *Version*: \n 2.2.24"
}
}
]
}
]
}
Author

Setup in App

In my case using MVVM pattern, some code that will be displayed is ViewModel and Model . use pod alamofire for hit API

  • ViewModel (Function for hit Api to webhook slack)
func getReportErrorToSlack(error: String, lineStr: Int, functionStr: String) {let baseWebHook = "https://hooks.slack.com/services/xxxxxx/xxxxxx/xxxxxxx"var blocks = [[String: Any]]()var attacments = [[String: Any]]()let block = MyAppModel.Block(username: "user test", errorCode: "404", message: error, line: lineStr, function: functionStr)blocks.append(block.parameters!)let attacment = MyAppModel.Attachment(blocks: blocks)attacments.append(attacment.parameters!)let parameters = MyAppModel.Request(attachments: attacments)
Alamofire.request(baseWebHook, method: .post, parameters: parameters.parameters, encoding: JSONEncoding.default).responseJSON { response inprint(response) }}// How to useself.getReportErrorToSlack(error: error.localizedDescription, lineStr: #line, functionStr: #function)
  • Model Request

public struct MyAppModel {

public struct Request {
let attachments: [[String: Any]]

var parameters: [String: Any]? {
return [
"attachments": attachments
]
}
}

public struct Attachment {
let blocks: [[String: Any]]

func parameters() -> [String: Any] {
return [
"color": "#f2c744",
"blocks": blocks
]
}

}

public struct Block {

var username: String
var errorCode: String
var message: String
var line: Int
var function: String

var parameters: [String: Any]? {
return [
"type": "section",
"text": [
"type": "mrkdwn",
"text": "*username:* \n \(username) \n *error_code:* \n \(errorCode) \n *message_error:* \n \(message) \n *line_code:* \n \(line) \n *function:* \n \(function)"
]
]
}

}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store