I create a json like this and put it into website URL:
[{"categoryID":1,"parentID":0,"categoryName":"Tempat Makan","imageFile":"foodandbeverages.png","isTopCategory":false},{"categoryID":2,"parentID":0,"categoryName":"Mini Market","imageFile":"minimarket.png","isTopCategory":false},{"categoryID":3,"parentID":0,"categoryName":"ATM","imageFile":"atm.png","isTopCategory":false},{"categoryID":4,"parentID":0,"categoryName":"SPBU","imageFile":"gasstation.png","isTopCategory":false},{"categoryID":5,"parentID":0,"categoryName":"Penginapan","imageFile":"inn.png","isTopCategory":false},{"categoryID":6,"parentID":0,"categoryName":"Bengkel","imageFile":"workshop.png","isTopCategory":false},{"categoryID":7,"parentID":0,"categoryName":"Kesehatan","imageFile":"health.png","isTopCategory":false},{"categoryID":9,"parentID":0,"categoryName":"Percetakan","imageFile":"printing.png","isTopCategory":false},{"categoryID":10,"parentID":0,"categoryName":"Cafetaria","imageFile":"cafetaria.png","isTopCategory":false},{"categoryID":11,"parentID":0,"categoryName":"Bank","imageFile":"bank.png","isTopCategory":false},{"categoryID":13,"parentID":0,"categoryName":"Jasa","imageFile":"services.png","isTopCategory":false},{"categoryID":65,"parentID":0,"categoryName":"Tempat Belanja","imageFile":"shopping.png","isTopCategory":false},{"categoryID":66,"parentID":0,"categoryName":"Hiburan","imageFile":"entertainment.png","isTopCategory":false},{"categoryID":79,"parentID":0,"categoryName":"Perjalanan","imageFile":"travel.png","isTopCategory":false},{"categoryID":83,"parentID":0,"categoryName":"Tempat","imageFile":"places.png","isTopCategory":false},{"categoryID":89,"parentID":0,"categoryName":"Pendidikan","imageFile":"education.png","isTopCategory":false},{"categoryID":93,"parentID":0,"categoryName":"Kecantikan","imageFile":"beautyandspa.png","isTopCategory":false},{"categoryID":99,"parentID":0,"categoryName":"Rental","imageFile":"rent.png","isTopCategory":false},{"categoryID":105,"parentID":0,"categoryName":"Peliharaan","imageFile":"pet.png","isTopCategory":false}]
I try to put categoryID, categoryName and imageFile into collection view with code like these:
struct country
{
var imageFile:String!
var categoryName:String!
var categoryID:Int!
init(categoryID:Int, categoryName:String, imageFile:String)
{
self.imageFile = imageFile
self.categoryName = categoryName
self.categoryID = categoryID
}
}
var Data:Array< country > = Array < country >()
override func viewDidLoad() {
super.viewDidLoad()
collectionview.dataSource = self
collectionview.delegate = self
let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top:1,left:10,bottom:10,right:10)
layout.minimumInteritemSpacing = 5
layout.minimumLineSpacing = 10
collectionview.collectionViewLayout = layout
get_data_from_url("http://domain/category.json")
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CategoryCell
let bcolor : UIColor = UIColor( red: 0.2, green: 0.2, blue:0.2, alpha: 0.3 )
cell.layer.borderColor = bcolor.CGColor
cell.layer.borderWidth = 0.5
cell.layer.cornerRadius = 3
cell.backgroundColor=UIColor.whiteColor()
cell.text.text = "\(Data[indexPath.row].categoryID)"
cell.country.text = Data[indexPath.row].categoryName
let gambar_categorynya = "http://domain/category/\(Data[indexPath.row].imageFile)"
print("gambar_categorynya:\(gambar_categorynya)")
cell.imageCategory.image = UIImage(data: NSData(contentsOfURL: NSURL(string:"http://domain/category/\(Data[indexPath.row].imageFile)")!)!)
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return Data.count
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: 100 , height: 50)
}
and extract json data like this:
func extract_json(data:NSString)
{
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject?
do {
json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
} catch let error as NSError {
parseError = error
json = nil
}
if (parseError == nil)
{
if let countries_list = json as? NSArray
{
for (var i = 0; i < countries_list.count ; i++ )
{
if let country_obj = countries_list[i] as? NSDictionary
{
if let country_image = country_obj["imageFile"] as? String
{
if let country_name = country_obj["categoryName"] as? String
{
if let country_code = country_obj["categoryID"] as? Int
{
let add_it = country(categoryID: country_code, categoryName: country_name, imageFile: country_image)
Data.append(add_it)
}
}
}
}
}
}
}
do_refresh();
}
func do_refresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.collectionview.reloadData()
return
})
}
func get_data_from_url(url:String)
{
let httpMethod = "GET"
let timeout = 15
let url = NSURL(string: url)
let urlRequest = NSMutableURLRequest(URL: url!,
cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 15.0)
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(
urlRequest,
queue: queue,
completionHandler: {(response: NSURLResponse?,
data: NSData?,
error: NSError?) in
if data != nil && error == nil{
let json = NSString(data: data!, encoding: NSASCIIStringEncoding)
self.extract_json(json!)
}
}
)
}
my last looping print stop at gambar_categorynya:http://domain/category/travel.png
after that it thrown error : fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)
and the error (red signal) at this line:
cell.imageCategory.image = UIImage(data: NSData(contentsOfURL: NSURL(string:"http://domain/category/\(Data[indexPath.row].imageFile)")!)!)
how to correct this?
info: imageFile always string so even i put string! it still trown me error fatal error: unexpectedly found nil while unwrapping an Optional value (lldb). I already got all categoryID and categoryName. this is collectionview cell:
class CategoryCell: UICollectionViewCell {
@IBOutlet var text: UILabel!
@IBOutlet var country: UILabel!
@IBOutlet weak var imageCategory: UIImageView!
}