Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func findContactId(withEmail email: String) -> [Int] {
- let resource = Resource<[Int]>.init(method: .GET,
- path: ApiPath.contactsFilterByEmail + email,
- json: nil) { (result) -> [Int] in
- let json = (try! JSONSerialization.jsonObject(with: result, options: [])) as? [String: [Int]]
- return (json?["ContactIdentifiers"]! }
- return performRequest(resource)!
- }
- private struct Resource<T> {
- let method: HttpMethod
- let path: String
- let json: Data?
- let parser: (Data) -> T
- }
- enum HttpMethod {
- case GET
- case POST
- case PUT
- }
- private func performRequest<T>(resource: Resource<T>) -> T {
- let url = URL(string: "\(apiHost)/\(account.id)/\(path)")!
- var request = URLRequest(url: url)
- if json != nil {
- request.httpBody = json
- request.setValue("application/json", forHTTPHeaderField: "Content-Type")
- }
- request.setValue("Bearer \(getToken())", forHTTPHeaderField: "Authorization")
- request.httpMethod = "\(method)"
- var result: Data?
- let semaphore = DispatchSemaphore(value: 0)
- URLSession.shared.dataTask(with: request) { data, response, error in
- guard let data = data, error == nil else {
- self.fail(withMessage: error?.localizedDescription ?? "No error data")
- return
- }
- if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
- self.fail(withMessage: "StatusCode should be 200, but is \(httpStatus.statusCode)")
- }
- result = data
- semaphore.signal()
- }.resume()
- semaphore.wait()
- return result
- }
Advertisement
Add Comment
Please, Sign In to add comment