user616076 user616076 - 11 months ago 70
reST (reStructuredText) Question

My session.dataTaskWithRequest method is not returning any data

I need to interrogate our Api to populate our main screen, so I set up a separate class called RestApiManager and added the code below

import UIKit

class RestApiManager: NSObject {
static let sharedInstance = RestApiManager()

let baseURL = ""

func getData() {
let request = NSMutableURLRequest(URL: NSURL(string: baseURL)!)
let session = NSURLSession.sharedSession()

let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if data != nil {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary //:JSON = JSON(data: jsonData)
}catch _ as NSError


I used the url shown as a simple test, as I know it returns data without any properties as i tested it in my browser but each time I run my app the data is always nil.

What am I doing wrong?


Since this is a Http request you need to add NSTransportSecurity in your info.plist. Hope you have done that.

If you haven't done that. Visit this Link

Also you need to tell the request method i.e. .GET in your case.

let headers = ["cache-control": "no-cache"]

var request = NSMutableURLRequest(URL: NSURL(string: "")!,
                                        cachePolicy: .UseProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.HTTPMethod = "GET"
request.allHTTPHeaderFields = headers

let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
  } else {
    let httpResponse = response as? NSHTTPURLResponse


This is working for me and might also work for you.