调用API时,不显示UICollectionView单元格

时间:2015-12-28 08:56:25

标签: ios uicollectionview swift2 uicollectionviewcell swifty-json

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

查看控制器:

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。任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

首先,我没有看到你设置dataSource和委托。

尝试

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

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

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