Skip to main content
4 of 5
added link to Alamofire
saurabh
  • 156
  • 3
  • 18

Asynchronous HTTP JSON request

For asynchronous requests, I use Alamofire. I have created one method for requesting async data.

func requestData(method: Method, urlString: String, onSuccess: (AnyObject) -> Void , onFailure: (NSError) -> Void,  sender: UIViewController, postParams:AnyObject? = nil) {

let internetAvailable = Reachability.isConnectedToNetwork()    
if(internetAvailable) {
    let AFmanager = Manager(configuration: seesionConfiguration)
    
    let URL = NSURL(string: urlString)!
    let urlRequest = NSMutableURLRequest(URL: URL)
    urlRequest.HTTPMethod = method.rawValue
    
    if let param: AnyObject = postParams {
        urlRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(param, options: nil, error: nil)
    }
    if method == .POST {
        urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
    }
    urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")

    AFmanager.request(urlRequest)
        .responseJSON { (request, response, JSONResult, error) in
            if (error == nil) {
                onSuccess(JSONResult!)
            } else {
                onFailure(error!)
            }
    } else {
    Alert.showAlert("No Internet", message: "You appear to be offline, please Retry", buttonTitle: "OK", sender: sender)
}

Here, I have made postParams of type AnyObject as parameter can be of any dictionary type. Is there another way of defining the method so that postParams can be checked to be of type dictionary?

Any other improvement/suggestion?

saurabh
  • 156
  • 3
  • 18