Created
April 6, 2017 17:54
-
-
Save dmsl1805/2a6b90240c1fdc491e7209c00121d9af to your computer and use it in GitHub Desktop.
This file contains 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
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