Created
June 28, 2015 15:51
-
-
Save kiichi/bcf6ecb75a9312e903ec to your computer and use it in GitHub Desktop.
Swift Slack Integration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// icon | |
// http://www.emoji-cheat-sheet.com/ | |
// for test use direct message e.g. @kiichi | |
let payload = "payload={\"channel\": \"#dev\", \"username\": \"bot\", \"icon_emoji\":\":calling:\", \"text\": \"hello\"}" | |
let data = (payload as NSString).dataUsingEncoding(NSUTF8StringEncoding) | |
if let url = NSURL(string: "https://hooks.slack.com/services/(your slack incoming webhook url)") | |
{ | |
var request = NSMutableURLRequest(URL: url) | |
request.HTTPMethod = "POST" | |
request.HTTPBody = data | |
let session = NSURLSession.sharedSession() | |
let task = session.dataTaskWithRequest(request){ | |
(data, response, error) -> Void in | |
if error != nil { | |
println("error: \(error.localizedDescription): \(error.userInfo)") | |
} | |
else if data != nil { | |
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) { | |
println("\(str)") | |
} | |
else { | |
println("error") | |
} | |
} | |
} | |
task.resume() | |
} | |
else { | |
println("url invalid") | |
} |
Thanks @kiichi! Here is modified for swift 3:
let payload = "payload={\"channel\": \"#dev\", \"username\": \"bot\", \"icon_emoji\":\":calling:\", \"text\": \"hello\"}"
let data = payload.data(using: .utf8)!
if let url = NSURL(string: "https://hooks.slack.com/services/(your slack incoming webhook url)")
{
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.httpBody = data
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest){
(data, response, error) -> Void in
if error != nil {
print("error")
}
else if data != nil {
if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
print("\(str)")
}
else {
print("error")
}
}
}
task.resume()
}
else {
print("url invalid")
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!