-1

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 = "http://api.randomuser.me/"

   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
            {
            }
        } 
    })
    task.resume()
   }
}

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?

Bhumika
  • 876
  • 7
  • 20
user616076
  • 3,907
  • 8
  • 38
  • 64

1 Answers1

1

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: "http://api.randomuser.me/")!,
                                        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) {
    println(error)
  } else {
    let httpResponse = response as? NSHTTPURLResponse
    println(httpResponse)
  }
})

dataTask.resume()

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

Community
  • 1
  • 1
Sanchit Kumar Singh
  • 513
  • 1
  • 5
  • 17