ios - 调用 API 时不显示 UICollectionView 单元格

标签 ios uicollectionview swift2 uicollectionviewcell swifty-json

我正在开发一个简单的应用程序,它将从 URL 中获取详细信息并将其检索到 UICollectionViewCell 中。我引用了很多 tuts,最后我使用了类似于 REST API。问题是,当它构建时,没有发现任何问题,而且 UICollectionView 单元格变为空。

View Controller :

import UIKit
class ImageViewController: UIViewController, NSURLConnectionDelegate, UICollectionViewDelegate, UICollectionViewDataSource {

var items = NSMutableArray()

@IBOutlet var colView: UICollectionView!

override func viewDidLoad()
{
    super.viewDidLoad()
    self.colView!.registerClass(NSClassFromString("ImageCollectionViewCell"),forCellWithReuseIdentifier:"collectionView");
    addUrlData()
}

func addUrlData()
{
        ImageManager.sharedInstance.getRandomUser { json in

        let results: JSON = json["share"][2]["data"]

        for(key, subJson) in results
        {
            let user: NSDictionary = subJson["shares"].object as! NSDictionary
            self.items.addObject(user)
            dispatch_async(dispatch_get_main_queue(),{
                colView?.reloadData()
            })
        }  
    }
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //return self.items.count;
    return 10

}



func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let row = indexPath.row
    var cell: ImageCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionView", forIndexPath: indexPath) as! ImageCollectionViewCell

    if cell == []
    {
        print("UIColViewCell Error")
    }

    let user:JSON = JSON(self.items[row])
    let picURL = "http://buddysin.aumkiiyo.com/thumb/" + user["mid"]["image"].string! + "/" + " \(245)"   // Image URL
    print(picURL)
    let url = NSURL(string: picURL)
    if let data = NSData(contentsOfURL: url!)
    {
        cell.imageLabel?.text = user["name"].string
        cell.imageView?.image = UIImage(data: data)

        //   let shareItem: Shares = ImageManager.sharedInstance.imageListArray[row]
        cell.backgroundColor = UIColor.blackColor()
    }
    //  cell.imageLabel?.text = String(shareItem.latitude!)
    return cell
}


}

图像管理器:

typealias ServiceResponse = (JSON, NSError?) -> Void

class ImageManager: NSObject {
    static let sharedInstance = ImageManager()

    let baseURL = "http://buddysin.aumkiiyo.com/api/nearby/share"

    func getRandomUser(onCompletion: (JSON) -> Void) {
        let route = baseURL
        makeHTTPGetRequest(route, onCompletion: { json, err in
           onCompletion(json as JSON)     })

    }

    func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) {
        let request = NSMutableURLRequest(URL: NSURL(string: path)!)

        let session = NSURLSession.sharedSession()

        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            let json:JSON = JSON(data: data!)

            onCompletion(json, error)
            if error != nil
                {
                    print("***** NSUrlSession error=\(error)")
                    return
            }

            //You can print out response object
            print("******** Response object = \(response)")

            //Print out response body
            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("******** Response body = \(responseString)")

        })
        task.resume()
    }
    //MARK: Perform a POST Request
    func makeHTTPPostRequest(path: String, body: [String: AnyObject], onCompletion: ServiceResponse) {
        //var err: NSError?
        let request = NSMutableURLRequest(URL: NSURL(string: path)!)
        // Set the method to POST
        request.HTTPMethod = "POST"

        // Set the POST body for the request
        do {
            request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(body, options: [])
            let session = NSURLSession.sharedSession()
            let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
                let json:JSON = JSON(data: data!)
                onCompletion(json, error)
                if error != nil
                {
                    print("***** NSUrlSession error=\(error)")
                    return
                }

         //       //You can print out response object
           //     print("******** Response object = \(response)")

                //Print out response body
                let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("******** Response body = \(responseString)")


            })
            task.resume()
        } catch {
            print("error:\(error)")
        }
    }
}

此应用程序的库是:SwiftyJSON。谁能帮我解决这个问题?

最佳答案

首先,我没有看到您设置数据源和委托(delegate)。

尝试

self.colView!.dataSource = self // dataSource delegate
self.colView!.delegate = self  // UICollectionView delegate

其次,您不必每次都调用reloadData()。您只需在数据准备就绪时调用它,它就会重新加载所有数据。

另一件事是,确保 JSON(self.items[row]) 在调用 cellForItemAtIndexPath 时具有数据。如果您的 HTTP 请求是异步的,请在您的完成处理程序中调用 reloadData,如果没有发生错误,就像在 onCompletion(json, error) 中一样。

关于ios - 调用 API 时不显示 UICollectionView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34490411/

相关文章:

ios - 无法调用非函数类型的值'((成功 : Bool, 错误 : NSError?)抛出 -> Void)?)

ios - 如何通过 alamofire 4 和 swift 3 提供身份验证 token 以登录 api

ios - 动画似乎不起作用 - 在 [self dismiss ViewController] 上将 View 从一个位置移动到另一个位置

ios - 如何仅在复合 UIView 的一部分应用 3D 透视变换?

swift - 支持 iOS 12 和 13 时的 UITableView 和 Diffable 数据源

ios - 如何在 swift 2 中增加单元格内按钮点击操作的行高

swift 2 : Cannot convert value of type '[NSObject : AnyObject]' to expected argument type '[String : AnyObject]'

ios - 键值 NSDictionary 的 SBJSON 问题

ios - 重新加载后 uicollectionviewcell 标签未对齐

ios - 协议(protocol)功能在 swift 3 中不起作用