user3497437 user3497437 - 28 days ago 6
iOS Question

Not able to hit the endpoint when making a GET request in swift

Hello i am trying to make a get request from my server but i am failing to hit the endpoints as i checked my logs and im not even hitting the final endpoint. The endpoint needs an authorization which has been added to the request field. I am attempting to get json values and display them as a table cell. But when i attempt to retrieve the values it return nil. It never attempts to hit the endpoint. I attempted to put a print statement

print("Session)"
to check if it calls dataWithRequest but if fails to do so. Please i am doing anything wrong here?

func getLocalData() -> [[String:AnyObject]] {
var json:[[String:AnyObject]]?
let endPoint = "http://******************"

let url:NSURL? = NSURL(string: endPoint)
let session = NSURLSession.sharedSession()

let request:NSMutableURLRequest = NSMutableURLRequest(URL: url!)

request.HTTPMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(token!, forHTTPHeaderField: "Authorization-Header")


let task = session.dataTaskWithRequest(request) {(data, response, error) -> Void in
print("Session") //not able to get in here
guard let data = data where error == nil else {
//network error
print("Error with network: \(error?.localizedDescription)")
return
}

let httpResponse = response as! NSHTTPURLResponse//HTTPURLResponse
let statusCode = httpResponse.statusCode

if statusCode == 200 {
do {
print("Here buddy")
json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]]
// return json
}

catch {
print("Error in json")
}
}
}

task.resume()

print("JSON: \(json)") //prints nil as it never attempts to make the request to the server

return json
}


and in my TableListController i attempt to call this function and it complains about the
fatal error: unexpectedly found nil while unwrapping an Optional value


class DealListController: UITableViewController {
let myDeals = DealList()
var dealsArray = []

override func awakeFromNib() {
super.awakeFromNib()
dealsArray = myDeals.getLocalData()! //complains about error here
}
}

Answer

Let add these things into your Info.plist enter image description here

Update: Let use completion handler instead of returning a value

func getLocalData(completion: (json: [[String:AnyObject]]?) -> Void) {
    let endPoint = "http://******************"

    let url:NSURL? = NSURL(string: endPoint)
    let session = NSURLSession.sharedSession()

    let request:NSMutableURLRequest = NSMutableURLRequest(URL: url!)

    request.HTTPMethod = "GET"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("", forHTTPHeaderField: "Authorization-Header")


    let task = session.dataTaskWithRequest(request) {(data, response, error) -> Void in
        print("Session") //not able to get in here
        guard let data = data where error == nil else {
            //network error
            print("Error with network: \(error?.localizedDescription)")
            completion(json: nil)
            return
        }

        let httpResponse = response as! NSHTTPURLResponse//HTTPURLResponse
        let statusCode = httpResponse.statusCode

        if statusCode == 200 {
            do {
                print("Here buddy")
                let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]]
                // return json
                completion(json: json)
            }

            catch {
                print("Error in json")
                completion(json: nil)
            }
        }
    }

    task.resume()
}

And:

myDeals.getLocalData { json in
    print("json: \(json)")
    dealsArray = json!
}
Comments