UICollectionView 中的 Alamofire + Swift
Alamofire + Swift in UICollectionView
我不知道如何使用 Alamofire 解析 JSON 数据。现在我成功地从网络服务请求数据。问题是我不太确定如何将 embed/parse 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"
}]
}
首先,我假设您的 UICollectionView 中有一些 UIImageView,否则您首先需要它。
解析 json 数据并获得图像 url 后,您需要使用另一个库来下载实际图像。我发现 SDWebImageDownloader (https://github.com/rs/SDWebImage) 对这项任务很有用。该库位于 objective C 中,因此您必须使用桥接头。
var url: NSURL = NSURL(string: self.detailsData.ownerImage)!
SDWebImageDownloader.sharedDownloader().downloadImageWithURL(url, options: nil, progress: nil, completed: {(image: UIImage?, data: NSData?, error: NSError?, finished: Bool) in
if (image != nil) {
//Do something with your image. This is now UIImage
}
})
另一个是 (https://github.com/Haneke/HanekeSwift)。我没有亲自使用过它,但看起来这就是你所做的。但是,这个在 swift 中,因此您先尝试这个可能更容易。从文档来看,它们似乎扩展了 UIImageView,因此您应该可以使用这些方法。
// Setting a remote image
imageView.hnk_setImageFromURL(url)
// Setting an image manually. Requires you to provide a key.
imageView.hnk_setImage(image, key: key)
希望对您有所帮助。
我已经找到了解决方案。
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!)
}
}
}
@Dato' Mohammed Nurdin
如果你使用 Swiftyjson,这将起作用,如果你想下载图像,我建议你在 Alamofire 框架中扩展 Request 并构建你自己的 responseImage 函数,如下所示:
extension Alamofire.Request {
class func imageResponseSerializer() -> Serializer {
return { request, response, data in
if data == nil {
return (nil, nil)
}
let image = UIImage(data: data!, scale: UIScreen.mainScreen().scale)
return (image, nil)
}
}
func responseImage(completionHandler: (NSURLRequest, NSHTTPURLResponse?, UIImage?, NSError?) -> Void) -> Self {
return response(serializer: Request.imageResponseSerializer(), completionHandler: { (request, response, image, error) in
completionHandler(request, response, image as? UIImage, error)
})
}
}
我不知道如何使用 Alamofire 解析 JSON 数据。现在我成功地从网络服务请求数据。问题是我不太确定如何将 embed/parse 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"
}]
}
首先,我假设您的 UICollectionView 中有一些 UIImageView,否则您首先需要它。
解析 json 数据并获得图像 url 后,您需要使用另一个库来下载实际图像。我发现 SDWebImageDownloader (https://github.com/rs/SDWebImage) 对这项任务很有用。该库位于 objective C 中,因此您必须使用桥接头。
var url: NSURL = NSURL(string: self.detailsData.ownerImage)!
SDWebImageDownloader.sharedDownloader().downloadImageWithURL(url, options: nil, progress: nil, completed: {(image: UIImage?, data: NSData?, error: NSError?, finished: Bool) in
if (image != nil) {
//Do something with your image. This is now UIImage
}
})
另一个是 (https://github.com/Haneke/HanekeSwift)。我没有亲自使用过它,但看起来这就是你所做的。但是,这个在 swift 中,因此您先尝试这个可能更容易。从文档来看,它们似乎扩展了 UIImageView,因此您应该可以使用这些方法。
// Setting a remote image
imageView.hnk_setImageFromURL(url)
// Setting an image manually. Requires you to provide a key.
imageView.hnk_setImage(image, key: key)
希望对您有所帮助。
我已经找到了解决方案。
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!)
}
}
}
@Dato' Mohammed Nurdin 如果你使用 Swiftyjson,这将起作用,如果你想下载图像,我建议你在 Alamofire 框架中扩展 Request 并构建你自己的 responseImage 函数,如下所示:
extension Alamofire.Request {
class func imageResponseSerializer() -> Serializer {
return { request, response, data in
if data == nil {
return (nil, nil)
}
let image = UIImage(data: data!, scale: UIScreen.mainScreen().scale)
return (image, nil)
}
}
func responseImage(completionHandler: (NSURLRequest, NSHTTPURLResponse?, UIImage?, NSError?) -> Void) -> Self {
return response(serializer: Request.imageResponseSerializer(), completionHandler: { (request, response, image, error) in
completionHandler(request, response, image as? UIImage, error)
})
}
}