我像这样创建一个json并将其放入网站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}]
我尝试将categoryID,categoryName和imageFile放入集合视图中,其代码如下:
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)
}
并提取这样的json数据:
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!)
}
}
)
}
我在gambar_categorynya的最后一次循环打印停止:http://domain/category/travel.png
之后抛出错误:致命错误:在展开Optional值时意外发现nil (LLDB)
和此行的错误(红色信号):
cell.imageCategory.image = UIImage(data: NSData(contentsOfURL: NSURL(string:"http://domain/category/\(Data[indexPath.row].imageFile)")!)!)
如何纠正这个?
info:imageFile总是字符串,所以即使我把字符串!它仍然告诉我错误致命错误:在解开一个Optional值时意外地发现了nil (LLDB)。我已经获得了所有categoryID和categoryName。 这是collectionview单元格:
class CategoryCell: UICollectionViewCell {
@IBOutlet var text: UILabel!
@IBOutlet var country: UILabel!
@IBOutlet weak var imageCategory: UIImageView!
}