1

How can I convert my current Alamofire request into a synchronous request? Will this stop all other execution until the request completes?

MY current function is as follows:

func updateLabels() {
    Alamofire.request(apiUrl).responseJSON { response in
        if let data = response.result.value {
            var rawJson = JSON(data)
            var json = rawJson[0]

            var totalViews = json["totalViews"].stringValue
            var uniqueUsers = json["uniqueUsers"].stringValue

            print(totalViews)
            print(uniqueUsers)

            self.totalViews.setText(totalViews)
            self.uniqueUsers.setText(uniqueUsers)
        }
    }
}

I'm using Alamofire_Synchronous. I'm not super familiar with Alamofire so any help would be awesome, thanks!

Joe Scotto
  • 10,936
  • 14
  • 66
  • 136
  • I think, this link will help you https://stackoverflow.com/questions/39961010/how-to-make-a-synchronous-request-using-alamofire – hament miglani Jun 05 '17 at 03:46

1 Answers1

2

You can use this extension and call sync request to Alamofire lib.

extension Alamofire.Manager {

    func syncRequest(URLRequest: URLRequestConvertible) -> Response<AnyObject, NSError> {

        var outResponse: Response<AnyObject, NSError>!
        let semaphore: dispatch_semaphore_t! = dispatch_semaphore_create(0)

        self.request(URLRequest).responseJSON { (response: Response<AnyObject, NSError>) -> Void in

            outResponse = response
            dispatch_semaphore_signal(semaphore)
        }
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

        return outResponse
    }
}
ERbittuu
  • 968
  • 8
  • 19