-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathApiClient.swift
60 lines (49 loc) · 2.13 KB
/
ApiClient.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//
// ApiClient.swift
// FOSSAsia
//
// Created by Pratik Todi on 27/02/16.
// Copyright © 2016 FossAsia. All rights reserved.
//
import Foundation
typealias ApiRequestCompletionHandler = (NSData?, Error?) -> Void
struct ApiClient {
static let url = "https://raw.githubusercontent.com/fossasia/open-event/master/testapi/event/1/"
let eventInfo: EventInfo
func sendGetRequest(completionHandler: ApiRequestCompletionHandler) {
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig)
let request = NSURLRequest(URL: NSURL(string: getUrl(eventInfo))!)
let task = session.dataTaskWithRequest(request) { (data, response, networkError) -> Void in
if let _ = networkError {
let error = Error(errorCode: .NetworkRequestFailed)
completionHandler(nil, error)
return
}
guard let unwrappedData = data else {
let error = Error(errorCode: .JSONSerializationFailed)
completionHandler(nil, error)
return
}
self.processResponse(unwrappedData, completionHandler: { (error) -> Void in
guard error == nil else {
completionHandler(nil, error)
return
}
completionHandler(unwrappedData, nil)
})
}
task.resume()
}
private func getUrl(eventInfo: EventInfo) -> String {
return ApiClient.url + eventInfo.rawValue
}
private func processResponse(data: NSData, completionHandler: CommitmentCompletionHandler) {
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = dir.stringByAppendingPathComponent(SettingsManager.getLocalFileName(eventInfo));
data.writeToFile(path, atomically: false)
completionHandler(nil)
}
completionHandler(Error(errorCode: .JSONSystemReadingFailed))
}
}