如何在从api获取数据时在表视图中显示第一个数据

时间:2016-05-03 13:10:33

标签: ios swift uitableview uicollectionview

我有一个集合视图,它有大约5个单元格。我从api中获取哪些内容以在集合视图中显示单元格数据。当用户单击任何单元格时,该适当的数据将显示在下表视图中。

现在,一切都运转正常。但是当我第一次加载我的观点时。我的表格视图中没有数据显示......我的意思是什么?默认情况下,集合视图单元格的第一个数据必须显示在tableview中。但我没有或无法展示。

如果我只点击任何单元格,我可以在表格视图中看到数据。但我需要的是 - 默认情况下,当我打开那个屏幕时,集合视图的第一个单元格必须显示在表视图中

怎么做?

这是我的代码:

@IBOutlet var BTCollectionView: UICollectionView!

    @IBOutlet var DLTableView: UITableView!

    var BTdata = [BTData]()

    var Dealsdata = [DealsData]()
override func viewDidLoad()
    {
        super.viewDidLoad()
 // nib for custom cell (table view)
        let nib = UINib(nibName:"DealsListTableCell", bundle: nil)
        DLTableView.registerNib(nib, forCellReuseIdentifier: "DealCell")

        ListBusinessTypes()
}
    // Values from Api for Business Types
    func ListBusinessTypes()
    {
        let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as! String

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

        let request = NSMutableURLRequest(URL: NSURL(string: "httpsome url")!,
                                          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)

                let ErrorAlert = UIAlertController(title: "Error", message: "Problem with internet connectivity or server, please try after some time", preferredStyle: UIAlertControllerStyle.Alert)

                // add an action (button)
                ErrorAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                // show the alert
                self.presentViewController(ErrorAlert, animated: true, completion: nil)
            }
            else
            {
                if let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? Dictionary<String,AnyObject>
                {
                    let success = json["success"] as? Int

                    if(success == 1)
                    {
                        if let typeValues = json["data"] as? [NSDictionary]
                        {
                            dispatch_async(dispatch_get_main_queue(),{

                                for item in typeValues
                                {
                                    self.BTdata.append(BTData(json:item))

                                    self.BTCollectionView.reloadData()
                                }
                            })
                        }
                    }
                    else
                    {
                        let message = json["message"] as? String

                        print(message)

                        let ServerAlert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert)

                        // add an action (button)
                        ServerAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                        // show the alert
                        self.presentViewController(ServerAlert, animated: true, completion: nil)
                    }
                }
            }
        })

        dataTask.resume()
    }

// Mark : Collection View Delegate and Datasource(Business Type)
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return BTdata.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        let cell: DDLCollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier("HCollectionCell", forIndexPath: indexPath) as! DDLCollectionCell
        cell.BTName.text = BTdata[indexPath.row].BTNames
        return cell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
        ListDeals(BTdata[indexPath.row].BTIds!)
    }


func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return 1
    }

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

    // calling each cell based on tap and users ( premium / non premium )
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let tabcell = tableView.dequeueReusableCellWithIdentifier("DealCell") as! DealsListTableCell

        tabcell.DealName.text = Dealsdata[indexPath.row].DealNames

        if let imgURL = NSURL(string: Dealsdata[indexPath.row].DealImageUrls!)
        {
            let request: NSURLRequest = NSURLRequest(URL: imgURL)

            let session = NSURLSession.sharedSession()

            let Imgtask = session.dataTaskWithRequest(request)
            {
                (data, response, error) -> Void in

                if (error == nil && data != nil)
                {
                    func display_image()
                    {
                        tabcell.DealImage.image = UIImage(data: data!)
                    }
                    dispatch_async(dispatch_get_main_queue(), display_image)
                }
            }
            Imgtask.resume()
        }
        else
        {
            tabcell.DealImage.image = UIImage(named: "FBLogo")
        }

        let formatter = NSDateFormatter()
        formatter.locale = NSLocale(localeIdentifier: "en_US")
        formatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss.SSSSxxx"

        let date = formatter.dateFromString(Dealsdata[indexPath.row].DealExpiry!)

        let dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = .MediumStyle
        dateFormatter.timeStyle = .NoStyle
        dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
        let FormattedDate = dateFormatter.stringFromDate(date!)

        tabcell.RegPriceLabel.text = String(Dealsdata[indexPath.row].DealRegularPrice!)

        tabcell.SalePriceLabel.text = String(Dealsdata[indexPath.row].DealSalePrice!)

        tabcell.DealExpiryDate.text = "Expiries on : "+FormattedDate

        let BArrayValue:NSDictionary = Dealsdata[indexPath.row].DealBusinessDetails!

        let BName = BArrayValue.valueForKey("business_name") as! String

        let BImage = BArrayValue.valueForKey("images") as! NSArray

        let BMainImage = BImage[0] as! NSDictionary

        let FinalImage = BMainImage.valueForKey("url") as! String

        if let imgURL2 = NSURL(string: FinalImage)
        {
            let request: NSURLRequest = NSURLRequest(URL: imgURL2)

            let session = NSURLSession.sharedSession()

            let Imgtask = session.dataTaskWithRequest(request)
            {
                (data, response, error) -> Void in

                if (error == nil && data != nil)
                {
                    func display_image()
                    {
                        tabcell.DealBusinessImage.image = UIImage(data: data!)
                    }
                    dispatch_async(dispatch_get_main_queue(), display_image)
                }
            }
            Imgtask.resume()
        }
        else
        {
            tabcell.DealBusinessImage.image = UIImage(named: "FBLogo")
        }


        let BLatLng = Dealsdata[indexPath.row].DealCoordinates

        let UserLocation = CLLocation(latitude: NewCurrentLatitude, longitude: NewCurrentLongitude)

        let BusinessLocation = CLLocation(latitude: BLatLng![0] as! Double, longitude: BLatLng![1] as! Double)

        let distance = UserLocation.distanceFromLocation(BusinessLocation) / 1000

        tabcell.DealBusinessNameWithDistance.text = BName+" - "+String(format: "%.1f",distance)+" Km"

        return tabcell
    }

请帮帮我。谢谢!

我需要更改下面的任何内容:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
        ListDeals(BTdata[indexPath.row].BTIds!)
    }

1 个答案:

答案 0 :(得分:0)

尝试从API加载数据后调用ListDeals(BTdata[0].BTIds!)

...

if let typeValues = json["data"] as? [NSDictionary]
                    {
                        dispatch_async(dispatch_get_main_queue(),{

                            for item in typeValues
                            {
                                self.BTdata.append(BTData(json:item))

                                self.BTCollectionView.reloadData()
                            }
                            ListDeals(BTdata[0].BTIds!)
                        })
                    }

...