Search code examples
iosswiftapialamofireswifty-json

Issues with calling an API taking too much time to get a response


I am calling API in iOS (swift). Everything works perfectly, but it's taking too much time while getting response approximately 40 or 60 seconds. I don't know why this is happening. Let me show you my API calling method:

Code

func userDetailAPI(){

    let preferences = UserDefaults.standard

    let uid = "u_id"
    let acctkn = "acc_tkn"


    if preferences.object(forKey: uid) == nil {
        //  Doesn't exist
    } else {
        let u_id = preferences.object(forKey: uid) as! String
        print(u_id)
        let acc_tkn = preferences.object(forKey: acctkn) as! String
        print(acc_tkn)

        let userprofile: [String : Any] = ["user_id":u_id,"access_token":acc_tkn]
        print(userprofile)
        Alamofire.request(userDetails, method: .post, parameters: userprofile).responseJSON { response in
                print("RESPONSE : \(response)")
                let result = response.result.value

            if result != nil{
                let data = result as! [String : AnyObject]


                let userdata = data["data"] as! NSDictionary

                let email = userdata["email"]
                let name = userdata["name"]
                let photo = userdata["photo"]
                //let u_type = userdata["user_type"]!
                self.lblUserName.text = name as? String
                self.lblEmailID.text = email as? String

                let proimgurl = NSURL(string: photo as! String)
                self.imgProPic.image = UIImage(data: NSData(contentsOf: proimgurl! as URL)! as Data)

                //  }
        }

    }
}
}

Please check and help me - is this the right method for API calling or is there any other, better way?


Solution

  • Hey by the way there is also alamofire image pod is available. https://github.com/Alamofire/AlamofireImage

    eg: do import AlamofireImage into your file and call image url like below:

    Alamofire.request(image_url, method: .get).responseImage(completionHandler: { (response) in
                            self.your_UIImage_variable.image = response.result.value
                        })