I am trying to connect my HTTP server to get data in JSON format. It connects and gets the data properly. I am able to print the data before task.resume()
but, it doesn't print after task.resume()
Also, the function returns empty object.
I tried saving it into a global variable before task.resume()
. So, I can use a getter method to get the data, but still returns empty.
Can you please tell me what I am doing wrong here. Thanks in advance
func getTicketInfo(rDate: String, rName: String) -> NSDictionary {
var obj = NSDictionary()
let request = NSMutableURLRequest(URL: NSURL(string: self.host)!)
request.HTTPMethod = "POST"
let postString = "&DriverName=\(self.username);&Password=\(self.password);&Function=getTicketPrintInvoiceInfo;&routeName=\(rName);&routeDate=\(rDate);";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)", terminator: "")
return
}
var parseError: NSError?
let parsedObject: AnyObject?
do {
parsedObject = try NSJSONSerialization.JSONObjectWithData(data!,
options: NSJSONReadingOptions.AllowFragments)
} catch let error as NSError {
parseError = error
parsedObject = nil
} catch {
fatalError()
}
obj = (parsedObject as? NSDictionary)!
//prints the object fine
print(obj)
}
task.resume()
//prints empty result
print(obj)
return obj;
}