【发布时间】:2015-12-28 08:56:24
【问题描述】:
我正在开发一个简单的应用程序,它会从 URL 中获取详细信息并检索到 UICollectionViewCell。我参考了很多 tuts',最后我使用了类似于 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。谁能帮我解决这个问题?
【问题讨论】:
-
在队列外尝试 colView?.reloadData() 和 for 循环。
-
您似乎没有设置collectionView数据源或明确委托代码。您介意确认您是否通过界面生成器完成此操作吗?
-
感谢您的建议。我只通过界面生成器完成了.. 我应该在哪里使用 colview?.reloaData() 使用 for 循环
标签: ios uicollectionview swift2 uicollectionviewcell swifty-json