Guest User

Untitled

a guest
Jul 19th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.97 KB | None | 0 0
  1.     func findContactId(withEmail email: String) -> [Int] {
  2.         let resource = Resource<[Int]>.init(method: .GET,
  3.                                      path: ApiPath.contactsFilterByEmail + email,
  4.                                      json: nil) { (result) -> [Int] in
  5.                                         let json = (try! JSONSerialization.jsonObject(with: result, options: [])) as? [String: [Int]]
  6.                                         return (json?["ContactIdentifiers"]! }
  7.        
  8.         return performRequest(resource)!
  9.     }
  10.    
  11.     private struct Resource<T> {
  12.         let method: HttpMethod
  13.         let path: String
  14.         let json: Data?
  15.         let parser: (Data) -> T
  16.     }
  17.    
  18.     enum HttpMethod {
  19.         case GET
  20.         case POST
  21.         case PUT
  22.     }
  23.  
  24.     private func performRequest<T>(resource: Resource<T>) -> T {
  25.         let url = URL(string: "\(apiHost)/\(account.id)/\(path)")!
  26.         var request = URLRequest(url: url)
  27.        
  28.         if json != nil {
  29.             request.httpBody = json
  30.             request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  31.         }
  32.        
  33.         request.setValue("Bearer \(getToken())", forHTTPHeaderField: "Authorization")
  34.         request.httpMethod = "\(method)"
  35.        
  36.         var result: Data?
  37.         let semaphore = DispatchSemaphore(value: 0)
  38.         URLSession.shared.dataTask(with: request) { data, response, error in
  39.             guard let data = data, error == nil else {
  40.                 self.fail(withMessage: error?.localizedDescription ?? "No error data")
  41.                 return
  42.             }
  43.            
  44.             if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
  45.                 self.fail(withMessage: "StatusCode should be 200, but is \(httpStatus.statusCode)")
  46.             }
  47.            
  48.             result = data
  49.             semaphore.signal()
  50.         }.resume()
  51.        
  52.         semaphore.wait()
  53.         return result
  54.     }
Advertisement
Add Comment
Please, Sign In to add comment