Skip to content

Instantly share code, notes, and snippets.

@murdockcrc
Created April 9, 2016 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save murdockcrc/796b4fc192f8dca171f742de6b3ca585 to your computer and use it in GitHub Desktop.
Save murdockcrc/796b4fc192f8dca171f742de6b3ca585 to your computer and use it in GitHub Desktop.
Posts batched events to an Event Hub endpoint
//
// Created by Luis Delgado on 4/5/16.
//
import Foundation
import Alamofire
class EventHub {
static let eventHubName = NSURL(string: "https://{yourNamespace}.servicebus.windows.net/{yourEventhubName}")!
static let publisherId = "{yourPublisherId}"
static var SasToken: String?
static var isTransmitting = false
class func serizalizeDataForBatchPosting(data: [[String : Double]]) -> [[String : String]] {
var arr = [[String : String]]()
for item in data {
let serializedInformation = try! NSJSONSerialization.dataWithJSONObject(item, options: NSJSONWritingOptions.init(rawValue: 0))
let serializedData = ["Body": String(data: serializedInformation, encoding: NSUTF8StringEncoding)!]
arr.append(serializedData)
}
return arr
}
class func postEvent(data: [[String : Double]], completionHandler: AlamofireCompletionHandler) {
let url = NSURL(string: "\(eventHubName)/publishers/\(publisherId)/messages?timeout=60&api-version=2014-01")!
let request = NSMutableURLRequest(URL: url)
request.setValue(NetworkHelper.sasToken, forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.microsoft.servicebus.json", forHTTPHeaderField: "Content-Type") //this is needed for batch posting of events
let body = serizalizeDataForBatchPosting(data)
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions.init(rawValue: 0))
request.HTTPMethod = "POST"
Alamofire.request(request).responseData { response in
if response.response?.statusCode == 401 {
NetworkHelper.getSasToken({ getSasTokenResponse in
if getSasTokenResponse.response?.statusCode == 200 {
EventHub.postEvent(data, completionHandler: completionHandler)
} else {
print("error getting sas token")
completionHandler(response)
}
})
} else {
completionHandler(response)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment