Zizoo
Zizoo

Reputation: 1754

Can't execute NSURLSession.sharedSession().dataTaskWithURL in Swift

I have a code to get an employee data from php returned Json which is the following :

[{"id":"1","email":"KK","password":"KKK","firstName":"KKK","lastName":"KK","photo":null,"phone":"22","mobile":"2","position":"SS","adminstrator_id":"1","department_id":"1"}]

Code I have try:

func getEmpById (id:String) {
    emp = employee()

    let myUrl = NSURL(string:"http://localhost/On%20Call%20App/scripts/getEmployee.php?id=\(id)")

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithURL(myUrl!, completionHandler: {
        (data, response, error) -> Void in

        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! [[String: AnyObject]]
            let dic = json[0]


            if let  id = dic["id"] , firstName = dic["firstName"] ,lastName = dic["lastName"], mobile = dic["mobile"],phone = dic["phone"],email=dic["email"],pos=dic["position"]{



                self.emp.setId(id as! String )

                self.emp.setFirstName(firstName as! String)

                self.emp.setLastName(lastName as! String)

                self.emp.setPhone(phone as! String)

                self.emp.setMobile(mobile as! String)

                self.emp.setEmail(email as! String)

                self.emp.setPosition(pos as! String)



            }


        } catch {
            print(error)

        }

    })
    task.resume()


}

The problem in this line let task = session.dataTaskWithURL(myUrl!, completionHandler:{ when the app reach this line it will directly go to task.resume() without printing any error

Any help to make this work ?

Upvotes: 0

Views: 251

Answers (1)

Nirav D
Nirav D

Reputation: 72410

Your response is of Array type not Dictionary

 let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray
 let dic = json[0] as! NSDictionary
 print(dic.objectForKey("email"))

It is batter if use use Swift array like this.

 let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! [[String: AnyObject]]
 let dic = json[0]
 print(dic["email"])

Upvotes: 1

Related Questions