1

I am new in Swift and the problem is I am getting data from webservices and then that data loads in tableview. In this process, websevices are working too slow it is taking 10 to 15 seconds because I have to download all images available in the webservices and add those in an array. This is necessary to download images but it also takes time, when all the data is loading at that time I am not able to click on back button and go to the previous page. But the code written by me is not working properly it takes more time to go back, it doesn't work instantly. Many times, I tap on the back button for two times, and so, it takes me to the second navigation (that means debug is not working instantly at back button ibAction).

Here is my code

Back Button 
@IBAction func click_back(sender: AnyObject)
    {
        //self.btn_Back.enabled = false;
        if let navController = self.navigationController {
            navController.popViewControllerAnimated(true)
        }else
        {
            //self.dismissViewControllerAnimated(true, completion: nil)
        }


    }
Calling API Like this 

let qualityOfServiceClass = QOS_CLASS_BACKGROUND
            let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
            dispatch_async(backgroundQueue, {
                print("This is run on the background queue")


            self.tag_getReplay = 0
            dispatch_async(dispatch_get_main_queue()) {



                self.ShowLoader()
            }




            let manager = AFHTTPRequestOperationManager()
            manager.GET(
                "\(WebServicesUrl.GlobalConstants.SiteUrl)get_jives.php?user_id=\(self.delegate.appd_userid)&at=\(self.delegate.token)&app_id=\(WebServicesUrl.AppID)&jive_id=\(self.getjive_id)",
                parameters: nil,
                success: { (operation: AFHTTPRequestOperation!,
                    responseObject: AnyObject!) in

                    do {
                        if let jsonResult:NSArray = responseObject as? NSArray
                        {

                            self.errorCheck = 0
                            let jsonArray = jsonResult as AnyObject as! NSMutableArray
                            self.arydata = NSMutableArray(array: jsonArray)
                            self.check_image_load = false;
                            self.check_image_load_height = false;
                            self.foundChannelForReplay = (self.arydata.objectAtIndex(0).valueForKey("channel_names") as? NSArray)!


                            let checkValue:Bool = self.checkcellPresent();
                                if(checkValue == true)
                                {
                            //print(checkValue)
                                let newIndex = NSIndexPath(forItem:3, inSection:0)
                                let threeTableViewCell = self.tbl_tranding.dequeueReusableCellWithIdentifier("cellthree", forIndexPath: newIndex) as! Cell_TJ_me_three

                                    for view in threeTableViewCell.subviews  {

                                        if let label = view as? UIButton {
                                            //print(label)
                                            //print("btn text == \(label.titleLabel?.text)")
                                            label.removeFromSuperview()
                                        }
                                        if let TheImage = view as? UIImageView {

                                            TheImage.removeFromSuperview()
                                        }
                                    }



                                }


                            let getReplayString = self.arydata.objectAtIndex(0).valueForKey("replies") as? String

                            //print(arydata.objectAtIndex(0))
                            self.ReplayToid = self.arydata.objectAtIndex(0).valueForKey("reply_to_id") as? String
                            if(self.ReplayToid == "0")
                            {// not comment then check rejive

                                self.ReplayToid = self.arydata.objectAtIndex(0).valueForKey("rejive_to_id") as? String
                            }
                            self.OrignalUserid = self.arydata.objectAtIndex(0).valueForKey("original_user_id") as? String
                            self.JiveUserid = self.arydata.objectAtIndex(0).valueForKey("user_id") as? String



                            let intValue : Int = NSString(string: getReplayString!).integerValue
                            let getImageArray:NSArray =  (self.arydata.objectAtIndex(0).valueForKey("images") as? NSArray)!
                            self.imageArray = NSMutableArray()
                            for var i = 0 ; i < getImageArray.count ; i++
                            {
                                let getimage:String = getImageArray.objectAtIndex(i) as! String
                                if let urlGet = NSURL(string: getimage) {

                                    if getimage.hasSuffix(".jpg") || getimage.hasSuffix(".png") || getimage.hasSuffix(".jpeg")
                                    {
                                        let data: NSData? = NSData(contentsOfURL: urlGet)
                                        if (data != nil)
                                        {
                                            var TheDownimage:UIImage!
                                            TheDownimage = UIImage(data: data!)
                                            self.imageArray.addObject(TheDownimage)
                                        }else
                                        {
                                            let TheDownimage:UIImage = UIImage(named:"img_error.png")!
                                            self.imageArray.addObject(TheDownimage)
                                        }
                                    }else
                                    {
                                        let TheDownimage:UIImage = UIImage(named:"img_error.png")!
                                        self.imageArray.addObject(TheDownimage)
                                    }
                                }else
                                {
                                    let TheDownimage:UIImage = UIImage(named:"img_error.png")!
                                    self.imageArray.addObject(TheDownimage)
                                }

                            }



                            if(intValue > 0)
                            {
                               //  dispatch_async(dispatch_get_main_queue()) {
                                self.Resent_Older = "1"
                                self.connection_getReplay()
                                //}

                            }else
                            {
                                self.Resent_Older = "0"
                               // dispatch_async(dispatch_get_main_queue()) {
                                self.tbl_tranding.separatorStyle = UITableViewCellSeparatorStyle.SingleLine



                                self.tbl_tranding.reloadData();
                                self.tbl_tranding.delegate=self;
                                self.tbl_tranding.dataSource=self;
                                self.hideLoader()
                             //   }

                            }

                            if(self.arydata.count > 0)
                            {

                                let geo_accuracy : String = self.arydata.objectAtIndex(0).valueForKey("geo_accuracy") as! String;
                                // print("geo_accuracy==\(geo_accuracy)")
                                if(geo_accuracy != "0")
                                {self.setmaplatLong()
                                }else
                                {
                                    self.innermapView.hidden = true
                                }

                            }

                        }else
                        {
                          dispatch_async(dispatch_get_main_queue()) {
                            self.hideLoader()
                            }
                            do {
                                if let jsonResult: Dictionary = responseObject as? Dictionary<String, AnyObject!>

                                {

                                    if ((jsonResult["Warning"]) != nil)
                                    {
                                        //print("YES")
                                    }else if ((jsonResult["Error"]) != nil)
                                    {
                                        //print("YES")
                                    }
                                    else if ((jsonResult["System"]) != nil)
                                    {
                                        let error_by_System:String  = jsonResult["System"] as! String
                                        let actionSheetController: UIAlertController = UIAlertController(title: "Warning", message:error_by_System, preferredStyle: .Alert)

                                        self.presentViewController(actionSheetController, animated: true, completion: nil)

                                        let cancelAction: UIAlertAction = UIAlertAction(title: "OK", style: .Cancel) { action -> Void in
                                            self.delegate.getFacebookName = ""
                                            self.delegate.getTwitterName = ""

                                            self.defaults.setObject("", forKey: "userid")
                                            self.defaults.setObject("", forKey: "userstatus")
                                            self.defaults.setObject("", forKey: "userimage")
                                            self.defaults.setObject("", forKey: "userfName")
                                            self.defaults.setObject("", forKey: "username")
                                            self.defaults.setObject("0", forKey: "Nicon")
                                            self.defaults.setObject("0", forKey: "Micon")
                                            self.defaults.setObject("", forKey: "token")

                                            self.delegate.tag_jive_channel_tab = 0
                                            self.delegate.token = "0";
                                            self.delegate.ary_channelList = NSArray()
                                            self.delegate.NotificationCount = 0
                                            self.delegate.MessageCount = 0




                                            if(self.delegate.signout_time_check_loader == 0)
                                            {
                                                self.delegate.loader = 1
                                            }



                                            // Direct in and then is work good
                                            let storyboard = UIStoryboard(name: "Main", bundle: nil)
                                            let initialViewController = storyboard.instantiateViewControllerWithIdentifier("FirstNavigation")
                                            UIApplication.sharedApplication().delegate?.window??.rootViewController = initialViewController
                                            UIApplication.sharedApplication().delegate?.window??.makeKeyAndVisible()

                                            //self.connection_sign_out()
                                            self.delegate.appd_userid = ""


                                            for object in (UIApplication.sharedApplication().windows.first)!.subviews
                                            {
                                                if let specificObj = object as? UIButton {
                                                    if(specificObj.tag  == 7001) // means fav button
                                                    {

                                                        specificObj.removeFromSuperview()
                                                    }
                                                }
                                            }


                                        }
                                        actionSheetController.addAction(cancelAction)

                                    }
                                }
                            }catch {

                                //print(error)

                            }


                        }
                    } catch {

                        //print(error)
                         dispatch_async(dispatch_get_main_queue()) {
                            self.hideLoader()
                        }

                    }



                },
                failure: { (operation: AFHTTPRequestOperation!,
                    error: NSError!) in
                    //print("Error:getAfnetworking: " + error.localizedDescription)
                    self.hideLoader()
                }
            )
            //en d
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    print("This is run on the main queue, after the previous code in outer block")
                })
            })

Please give me solution

tarzanbappa
  • 4,930
  • 22
  • 75
  • 117

1 Answers1

1

Use GCD / NSOperationQueue for more use this link. I recommend GCD ::

Asynchronous downloading of images for UITableView with GCD

Try to understand what GCD does and go ahead :

For your Problem >> Use it like

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {() -> Void in

    // time-consuming task(Code taking long time to load) in your case images


    dispatch_async(dispatch_get_main_queue(), {() -> Void in

    //display images or any other task which is referred as view things
    })
})

Keep thing in mind ther is clousure in the other clousure. Best of luck

Community
  • 1
  • 1
JAck
  • 854
  • 9
  • 18
  • If you will change priority right here in this situation this will work. But When you are working with more than two priorities than you have to mention all the priorities and its hierarchy. Please find the tutorial one by one and go ahead.. And yes if my answer helps you don't forget to up mark it... – JAck Jun 23 '16 at 07:21