从解析中查询图像和文本

时间:2016-01-14 22:31:52

标签: ios swift parse-platform

所以我创建了一个用户可以上传图像和文本的应用程序。帖子将显示在UICollectionView中我将提供一些代码供您查看。

所以我的PostsViewController看起来像这样:

import UIKit
import Parse
import Bolts
import ActiveLabel

extension UILabel {
    func setSizeFont (sizeFont: CGFloat) {
        self.font =  UIFont(name: self.font.fontName, size: sizeFont)!
        self.sizeToFit()
    }
}

extension NSDate {
    var timeAgo: String {
        let minute = 60
        let hour = 60 * minute
        let day = 24 * hour
        let secondsAgo = Int(NSDate().timeIntervalSinceDate(self))
        if secondsAgo < 0            { return  "later"                           }
        if secondsAgo == 0           { return "now"                              }
        if secondsAgo == 1           { return "1 second ago"                     }
        if secondsAgo < minute       { return "\(secondsAgo) seconds ago"        }
        if secondsAgo < (2 * minute) { return "1 minute ago"                     }
        if secondsAgo < hour         { return "\(secondsAgo/minute) minutes ago" }
        if secondsAgo < 2 * hour     { return "1 hour ago"                       }
        if secondsAgo < day          { return "\(secondsAgo / hour) hours ago"   }
        let formatter = NSDateFormatter()
        formatter.dateFormat = "M/d/yy"
        return formatter.stringFromDate(self)
    }
}

extension UIImage {
    func makeImageWithColorAndSize(color: UIColor, size: CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(CGRectMake(0, 0, size.width, size.height))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

struct Details {
    var username:String!
    var text:String!
    var CreatedAt:NSDate!
    var image:String!
    var objID:String!
    var likedBy:NSArray
    var comments:NSArray
    init(username:String,text:String,CreatedAt:NSDate,image:String,objID:String,likedBy:NSArray,comments:NSArray){

        self.username = username
        self.text = text
        self.CreatedAt = CreatedAt
        self.image = image
        self.objID = objID
        self.likedBy = likedBy
        self.comments = comments
    }
}

class HomeViewController: UIViewController, UICollectionViewDelegate, PlayerDelegate {

    @IBOutlet var collectionView: UICollectionView!

    var arrayOfDetails = [Details]()
    var likedPhotos = String()

    let Like = UIImage(named: "Like.png")
    let LikeDone = UIImage(named: "LikeDone.png")

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.collectionView.delegate = self

        queryCurrentUploads()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func queryCurrentUploads() {
        self.arrayOfDetails.removeAll()
        let query = PFQuery(className: "currentUploads")
        query.orderByDescending("createdAt")
        query.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error: NSError?) -> Void in
            if error == nil
            {
                if let newObjects = objects {

                    for oneobject in newObjects {
                        let text = oneobject["imageText"] as! String
                        let username = oneobject["username"] as! String
                        let objID = oneobject.objectId!
                        let time = oneobject.createdAt!
                        let likedBy = oneobject["likedBy"] as! NSArray
                        let comments = oneobject["comments"] as! NSArray


                        if let userImage = oneobject["imageFile"] as? PFFile {
                            let userImage = oneobject["imageFile"] as! PFFile

                            let imageURL = userImage.url
                            let OneBigObject = Details(username: username, text: text, CreatedAt: time, image: imageURL!, objID: objID, likedBy: likedBy, comments: comments)

                            self.arrayOfDetails.append(OneBigObject)

                            dispatch_async(dispatch_get_main_queue()) { self.collectionView.reloadData() }
                        }
                    }
                }
            }
        }
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return self.arrayOfDetails.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        let imageCell = collectionView.dequeueReusableCellWithReuseIdentifier("imageCell", forIndexPath: indexPath) as? CollectionViewCell

        let post = self.arrayOfDetails[indexPath.row]

        imageCell?.flagContentButton.titleLabel?.adjustsFontSizeToFitWidth = true
        imageCell?.uploadedTimeLabel.adjustsFontSizeToFitWidth = true
        imageCell?.commentsButton.titleLabel?.adjustsFontSizeToFitWidth = true

        imageCell?.likeButton.enabled = true

        if (self.arrayOfDetails.count > indexPath.row) {
            imageCell?.imageText.text = post.text
            imageCell?.imageText.numberOfLines = 0
            imageCell?.imageText.verticalTextAlignmentCenter = true
            imageCell?.imageText.minFontSize = 9

            imageCell?.likeButton.setTitle(post.likedBy.count.description, forState: UIControlState.Normal)

            imageCell?.commentsButton.setTitle("Comments(\(String(post.comments.count.description)))", forState: UIControlState.Normal)

            imageCell?.objectID.append(post.objID)
            imageCell?.uploadedTimeLabel.text = post.CreatedAt.timeAgo

            if (post.likedBy.containsObject((PFUser.currentUser()?.username)!!)){
                imageCell?.likeButton.setBackgroundImage(self.LikeDone, forState: UIControlState.Normal)
            }
            else{
                imageCell?.likeButton.setBackgroundImage(self.Like, forState: UIControlState.Normal)
            }

            imageCell?.imageView.setImageWithUrl(NSURL(string: post.image)!, placeHolderImage: UIImage(named: "Placeholder"))
        }
        return imageCell!
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSizeMake(UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.width+140)
    }
}

这是我的CollectionViewCell.swift:

import UIKit
import Parse
import ActiveLabel

class CollectionViewCell: UICollectionViewCell {

    @IBOutlet var imageView: UIImageView!
    @IBOutlet var imageText: ActiveLabel!
    @IBOutlet var uploadedTimeLabel: UILabel!
    @IBOutlet var flagContentButton: UIButton!
    @IBOutlet var likeButton: UIButton!
    @IBOutlet var commentsButton: UIButton!

    var objectID = [String]()
}

这就是我在Parse.com上课的方式: enter image description here

所以我的问题是:是否有更快或更简单/更简单的方法从Parse.com和我的UICollectionView获取数据?

1 个答案:

答案 0 :(得分:0)

编辑:我在下面添加了一些代码,以尽可能保持清洁。

你可以做的最重要的结构就是将收到的PFObjects放入一个数组中,并使用该数组来填充你的集合视图。我认为不需要解析那个辅助对象。

var spotsArray = [PFObject]()

func getParseData(){
    let query = PFQuery(className: "Places")
    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
        self.spotsArray = objects!
        self.spotsCollectionView.reloadData()
    }
    if refreshControl.refreshing {
        refreshControl.endRefreshing()
    }
}



func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return spotsArray.count
}

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

    let currentSpot = spotsArray[indexPath.row]

    cell.titleLabel.text = (currentSpot["Title"] as! String)

    if let descTemp = (currentSpot["Desc"] as? String){
        cell.descLabel.text = descTemp

        let userImageFile = currentSpot["imageFile"] as! PFFile
        userImageFile.getDataInBackgroundWithBlock {
            (imageData: NSData?, error: NSError?) -> Void in
            if error == nil {
                if let imageData = imageData {
                    cell.selectedImageView.image = UIImage(data:imageData)
                }

            } 
        }
    }

    return cell

}

上面的代码来自项目here.