Reputation: 189
I'm developing a simple App which would fetch the details from the URL and it retrieves into the UICollectionViewCell
. I refer many tuts' and finally I used similar to REST API. The problem is that, when it builds, no issues were found and also the UICollectionView
cell becomes empty.
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
}
}
Image Manager:
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)")
}
}
}
The library for this app is : SwiftyJSON
. Can any one help me to resolve this issue?
Upvotes: 1
Views: 777
Reputation: 9754
First of all, I don't see you setup the dataSource and delegate.
Try
self.colView!.dataSource = self // dataSource delegate
self.colView!.delegate = self // UICollectionView delegate
Second, you don't have to call reloadData()
every time. You just call it when your data is ready, it will reload all of it.
Another thing is, make sure JSON(self.items[row])
has the data when cellForItemAtIndexPath
is called. If your HTTP request is async, call reloadData
in your completion handler, like in onCompletion(json, error)
if no error occurred.
Upvotes: 1