gpt4 book ai didi

ios - UICollectionView 中的 Alamofire + Swift

转载 作者:行者123 更新时间:2023-11-28 11:20:36 25 4
gpt4 key购买 nike

我不知道如何使用 Alamofire 解析 JSON 数据。现在我成功地从网络服务请求数据。问题是我不太确定如何将 json(图像)数据嵌入/解析到 UICollectionView

import UIKit
import Alamofire

class PopularViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate {

var users: [AnyObject] = []

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
return users.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("UserCell", forIndexPath: indexPath) as PopularCollectionViewCell

Alamofire.request(.GET, "http://xxxxx/users.json").responseJSON { (_, _, data, _) in
println(data)

}
return cell
}

override func viewDidLoad() {
super.viewDidLoad()

}
}

Json 数据

{
"users": [{
"userId": 1,
"profilePhoto": "https://graph.facebook.com/1301454197/picture?type=large"
}]
}

最佳答案

我已经找到了解决方案。

PopularViewController.swift

import UIKit
import Alamofire

class PopularViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate {

var users: [JSON] = []
@IBOutlet var collectionView: UICollectionView!

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
return users.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("UserCell", forIndexPath: indexPath) as PopularCollectionViewCell

cell.user = self.users[indexPath.row]
return cell
}

override func viewDidLoad() {
super.viewDidLoad()

Alamofire.request(.GET, "xxxxx/users.json").responseJSON { (request, response, json, error) in

if json != nil {
var jsonObj = JSON(json!)
if let data = jsonObj["users"].arrayValue as [JSON]?{
self.users = data
self.collectionView.reloadData()
}
}

}
}
}

PopularCollectionViewCell.swift

import UIKit
import Haneke

class PopularCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var profilePicture:UIImageView!

var user:JSON?{
didSet{
self.setupUser()
}
}

func setupUser(){

if let urlString = self.user?["profilePhoto"]{
let url = NSURL(string: urlString.stringValue)
self.profilePicture.hnk_setImageFromURL(url!)
}

}
}

关于ios - UICollectionView 中的 Alamofire + Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28475389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com