Alamofire + Swift in UICollectionView

2019-08-28 21:24发布

I had no idea how to parse JSON data using Alamofire. Right now I successfully request the data from web service. The problem is I'm not really sure how to embed/parse json (image) data into 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 Data

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

Please advice. Thank you.

3条回答
smile是对你的礼貌
2楼-- · 2019-08-28 21:38

First, I am assuming you have some UIImageView inside your UICollectionView or else you will need that first.

Once you parse the json data and have the image urls, you need to use another library to download the actual image. I have found SDWebImageDownloader (https://github.com/rs/SDWebImage) being useful for this task. This library is in objective C so you have to use the bridging header.

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
    }
})

The other one being (https://github.com/Haneke/HanekeSwift). I have not personally used it but it looks like this is what you do. However, this one is in swift so it might be easier for you to try this one first. From the documentation, it looks like they extend UIImageView so you should have these methods available.

// Setting a remote image
imageView.hnk_setImageFromURL(url)

// Setting an image manually. Requires you to provide a key.
imageView.hnk_setImage(image, key: key)

I hope this helps.

查看更多
Viruses.
3楼-- · 2019-08-28 21:42

@Dato' Mohammed Nurdin This will work if you use Swiftyjson, if you want to download the image, I'd recommend you to extend the Request in the Alamofire framework and build your own responseImage function like this:

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)
        })
    }
}
查看更多
SAY GOODBYE
4楼-- · 2019-08-28 21:45

I already found the solution.

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!)
        }

    }
}
查看更多
登录 后发表回答