How can I make a function to call RESTful api through NSURLSESSION that can be used on every controller in swift iOS i.e. singleton object for everywhere in app This is the Code I came up with. But as soon as i call the method it crashes cause till return statement the jsonresponse is empty.
func apicall (mainurl : String, method :String,params :String ) -> NSDictionary{
var jsonresponse = NSDictionary()
let url:NSURL = NSURL(string: mainurl)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = method
// request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let paramString = params
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
enum JSONError: String, ErrorType {
case NoData = "ERROR: no data"
case ConversionFailed = "ERROR: conversion from JSON failed"
}
do{
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error")
throw JSONError.NoData
}
print("data = \(data), response = \(response) , error = \(error)")
guard let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary else {
throw JSONError.ConversionFailed
}
jsonresponse = json
}
catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}
task.resume()
return jsonresponse
}
}