Joe Scotto
Joe Scotto

Reputation: 10887

Convert Alamofire request to synchronous?

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!

Upvotes: 1

Views: 3142

Answers (1)

ERbittuu
ERbittuu

Reputation: 978

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
    }
}

Upvotes: 2

Related Questions