Swift如何在后台调用api中运行代码并在tableview中加载数据

时间:2016-06-22 09:39:38

标签: swift web-services api background

我是Swift的新手,问题是我从webservices获取数据,然后在tableview中加载数据。在这个过程中,web服务工作太慢,需要10到15秒,因为我必须下载webservices中可用的所有图像并将其添加到数组中。这是下载图像所必需的,但也需要时间,当时加载所有数据时我无法点击后退按钮并转到上一页。但是我编写的代码工作不正常需要更多时间才能返回,它不会立即生效。很多时候,我点击后退按钮两次,所以,它带我到第二个导航(这意味着调试不能立即在后退按钮ibAction工作)。

这是我的代码

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")
                })
            })

请给我解决方案

1 个答案:

答案 0 :(得分:1)

使用GCD / NSOperationQueue更多地使用此链接。我推荐GCD ::

Asynchronous downloading of images for UITableView with GCD

尝试了解GCD的作用并继续:

对于您的问题&gt;&gt;像

一样使用它
    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
    })
})

记住事情,在另一个clousure clousure。祝你好运