无法获取数据。或者在表格视图中获取两次相同的数据

时间:2016-04-25 11:20:58

标签: ios swift uitableview

我在表视图中显示来自一个url的数据。但是当我第一次打开时。我看到两次相同的数据或者有些时候我的表视图中没有数据显示。

import UIKit
import CoreLocation

class ContainerViewController: UIViewController, CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource {





    // check the current view controller
    weak var currentViewController: UIViewController?

    // show the location
    @IBOutlet weak var LocationLabel: UILabel!

    var locationManager: CLLocationManager = CLLocationManager()

    @IBOutlet var TypeLabel: UILabel!

    @IBOutlet var TableViewList: UITableView!



    var startLocation: CLLocation!


    var NewCurrentLatitude: Double!

    var NewCurrentLongitude: Double!

    var BTdata = BTData?()

    var BTypeId : String?

    // array to store the value from json
    var arrDict = [Businessdata]()


    var selectedIndex:NSIndexPath?

    override func viewDidLoad() {


        super.viewDidLoad()

        isSearching = false;

        locationManager.delegate = self

        locationManager.desiredAccuracy = kCLLocationAccuracyBest

        locationManager.requestWhenInUseAuthorization()



        startLocation = nil


        // nib for custom cell (table view)
        let nib = UINib(nibName:"customCell", bundle: nil)
        TableViewList.registerNib(nib, forCellReuseIdentifier: "cell")

       // LoadBusinesses()
    }

    override func viewDidAppear(animated: Bool)
    {
        self.TypeLabel.text = BTdata?.BTNames
        self.BTypeId = BTdata?.BTIds
         locationManager.startUpdatingLocation()

    }

    // current location
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location : CLLocationCoordinate2D = manager.location!.coordinate;
        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in

            if (error != nil)
            {
                print("Reverse geocoder failed with error" + error!.localizedDescription)
                return
            }

            if placemarks!.count > 0
            {
                let pm : CLPlacemark = placemarks![0]
                //stop updating location to save battery life

                let locality = (pm.locality != nil) ? pm.locality : ""

                let state = pm.administrativeArea

                let countryCode = pm.ISOcountryCode



                if(countryCode == "CAN")
                {
                    self.LocationLabel.text = "in "+locality!+", "+state!

                    self.NewCurrentLongitude = location.longitude;

                    self.NewCurrentLatitude = location.latitude;

                }
                else
                {
                    self.LocationLabel.text = "in Toronto, ON"

                    self.NewCurrentLatitude = 43.761539;

                    self.NewCurrentLongitude = -79.411079;

                    print("Manual location Label.")
                }

                self.locationManager.stopUpdatingLocation()

            }
            else
            {
                print("Problem with the data received from geocoder")
            }
             self.LoadBusinesses()

            NSUserDefaults.standardUserDefaults().setDouble(self.NewCurrentLongitude, forKey: "UserLongitude")

            NSUserDefaults.standardUserDefaults().setDouble(self.NewCurrentLatitude, forKey: "UserLatitude")

            NSUserDefaults.standardUserDefaults().synchronize()


        })




    }


    // location load failure
    func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
    {
        print("Error while updating location " + error.localizedDescription)
    }






    // web services method
    func LoadBusinesses()
    {
        print("Inside Load Business")

        let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as! String

        let headers = ["x-access-token": token]

        var StringUrl:String = "http:some url"

        StringUrl += "?lat=\(self.NewCurrentLatitude)"

        StringUrl += "&long=\(self.NewCurrentLongitude)"

        print(StringUrl)

        let request = NSMutableURLRequest(URL: NSURL(string: StringUrl)!,
                                          cachePolicy: .UseProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        request.HTTPMethod = "GET"
        request.allHTTPHeaderFields = headers

        let session = NSURLSession.sharedSession()
        let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
            if (error != nil)
            {
                print(error)
            }
            else
            {

                    if let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? NSDictionary
                    {
                        let success = json["success"] as? Int

                        if (success == 1)
                        {
                            if let reposArray = json["data"] as? [NSDictionary]
                            {
                                 self.arrDict.removeAll()
                                for item in reposArray
                                {
                                    let itemObj = item as? Dictionary<String,AnyObject>

                                    let b_type = itemObj!["business_type"]

                                    // taxis type
                                    if (b_type as? String == self.BTypeId)
                                    {
                                    self.arrDict.append(Businessdata(json:item))
                                    print("load data")


                                    }

                                }
                                dispatch_async(dispatch_get_main_queue(),{


                                    self.TableViewList.reloadData()

                                     print("load data 1")
                                })

                            }
                        }
                        else
                        {
                            let message = json["message"] as? String
                            print(message)
                        }
                    }

            }
        })
        dataTask.resume()
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
          print("load data 2")
        return self.arrDict.count


    }

    // number of rows
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return 1
    }



    // calling each cell based on tap and users ( premium / non premium )
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
           print("load data 3")

        let cell:customCell = self.TableViewList.dequeueReusableCellWithIdentifier("cell") as! customCell

        cell.vendorName.text = arrDict[indexPath.row].BusinessName
        cell.vendorAddress.text = arrDict[indexPath.row].Address
        cell.VendorRating.rating = arrDict[indexPath.row].Rating!

        return cell

    }

    // height of cell based on tap
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        if(isTapped == true && selectedIndex == indexPath)
        {
            return 125.0;
        }

        return 80.0;
    }

    // did select row of table view
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {

        selectedIndex = indexPath;

        isTapped = true;

        print("load data 4")
       // TableViewList.reloadData();

    }


}

我的完整代码。在同样的问题上我也面临着。同样的数据3次。在我的consloe中,打印功能也打印了两次。我测量了两次执行的功能:

load data 2
load data 2
load data 2
Manual location Label.
Inside Load Business
http://some url?lat=43.761539&long=-79.411079
load data
load data 2
load data 1
load data 3
0
1
2
3
4

1 个答案:

答案 0 :(得分:0)

您的代码应该是这样的。在解析数据后,您应该重新加载tableView。

if let reposArray = json["data"] as? [NSDictionary] {
    self.arrDict.removeAll()
    for item in reposArray {
        let itemObj = item as? Dictionary<String,AnyObject>
        let b_type = itemObj!["business_type"]
        // taxis type
        if (b_type as? String == self.BTypeId) {
            self.arrDict.append(Businessdata(json:item))
        }       
    }                   
    dispatch_async(dispatch_get_main_queue(),{
       self.TableViewList.reloadData()
    })
}