Skip to content

Instantly share code, notes, and snippets.

@dmsl1805
Created April 6, 2017 17:54
Show Gist options
  • Save dmsl1805/2a6b90240c1fdc491e7209c00121d9af to your computer and use it in GitHub Desktop.
Save dmsl1805/2a6b90240c1fdc491e7209c00121d9af to your computer and use it in GitHub Desktop.
func initializeDatabase() {
let request = NSMutableURLRequest(url: NSURL(string: "\(apiURL)/statistics/")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: callback)
dataTask.resume()
}
func addStatistic() {
let body = ["url": databaseURL, "user_id": "1251252", "point": "faculty", "date": "06.04.2017"]
var jsonBody: Data?
do {
jsonBody = try JSONSerialization.data(withJSONObject: body)
} catch {
}
let request = NSMutableURLRequest(url: NSURL(string: "\(apiURL)/statistics/add_statistics")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "PUT"
request.allHTTPHeaderFields = headers
request.httpBody = jsonBody
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: callback)
dataTask.resume()
}
func getStatistic() {
let body = ["url": databaseURL, "user_id": "1251252"]
var jsonBody: Data?
do {
jsonBody = try JSONSerialization.data(withJSONObject: body)
} catch {
}
let request = NSMutableURLRequest(url: NSURL(string: "\(apiURL)/statistics/get_statistics_general")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = jsonBody
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: callback)
dataTask.resume()
}
func callback(_ data: Data?, _ resp: URLResponse?, _ error: Error?) {
printResponse(resp, error: error)
parseResponse(data)
}
func parseResponse(_ data: Data?) {
if let jsonData = data {
do {
let json = try JSONSerialization.jsonObject(with: jsonData) as? Dictionary<String, Any>
print(json ?? "json is nil")
} catch let error{
print(error)
}
}
}
func printResponse(_ response: URLResponse?, error: Error?) {
if (error != nil) {
print(error!)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse ?? "response is nil")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment