gpt4 book ai didi

ios - 无法获取数据。或者在 TableView 中获取两次相同的数据

转载 作者:行者123 更新时间:2023-11-30 13:28:39 24 4
gpt4 key购买 nike

我在 TableView 中显示来自一个网址的数据。但是当我第一次打开时。我看到两次相同的数据,或者有时在我的 TableView 中没有显示数据。

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

最佳答案

你的代码应该是这样的。解析数据后,您应该重新加载 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()
})
}

关于ios - 无法获取数据。或者在 TableView 中获取两次相同的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36839108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com