Swift 3 - Receiving optional value when value be a string [duplicate] - swift

This question already has answers here:
Cannot get rid of Optional() string
(5 answers)
Closed 5 years ago.
So I have this code that takes the date of when a time was posted and converts it to something like "5h" or "1d" ago. However, it is displaying in my application as something like this - Optional(1)h.
Here is the code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "admincell", for: indexPath) as! AdminHomeCell
let post = activities[indexPath.row]
print(post["path"])
//let image = images[indexPath.row]
//let imaged = post["path"] as! String
//let image = URL(string: imaged)
let username = post["username"] as? String
let title = post["title"] as? String
let date = post["date"] as! String
let description = post["text"] as? String
let location = post["location"] as? String
let dateFormater = DateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd-HH:mm:ss"
let newDate = dateFormater.date(from: date)!
let from = newDate
let now = Date()
let components : NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfMonth]
let difference = (Calendar.current as NSCalendar).components(components, from: from, to: now, options: [])
if difference.second! <= 0 {
cell.postDate.text! = "now"
}
if difference.second! > 0 && difference.minute! == 0 {
cell.postDate.text! = "\(difference.second)s." // 12s.
}
if difference.minute! > 0 && difference.hour! == 0 {
cell.postDate.text! = "\(difference.minute)m."
}
if difference.hour! > 0 && difference.day! == 0 {
cell.postDate.text! = "\(difference.hour)h."
}
if difference.day! > 0 && difference.weekOfMonth! == 0 {
cell.postDate.text! = "\(difference.day)d."
}
if difference.weekOfMonth! > 0 {
cell.postDate.text! = "\(difference.weekOfMonth)w."
}
/*
let session = URLSession(configuration: .default)
let downloadPicTask = session.dataTask(with: image!) {
(data, response, error) in
if let e = error {
print("Error downloading image: \(e)")
} else {
if let res = response as? HTTPURLResponse {
if let image = data {
let pic = UIImage(data: image)
cell.postImage.image = pic
} else{
print("couldn't get image: image is nil")
}
} else {
print("Couldn't get response code")
}
}
}
*/
cell.postTitle.text = title
cell.postUser.text = username
cell.postDescription.text = description
cell.postLocation.text = location
cell.postDate.text = date
cell.postDescription.lineBreakMode = .byWordWrapping // or NSLineBreakMode.ByWordWrapping
cell.postDescription.numberOfLines = 0
//downloadPicTask.resume()
return cell
}
If there is anything I should change to make it simply display "1h", please let me know! Thanks!

Update Xcode to 8.3 or newer, there is a warning that you're printing an optional value instead of a normal one.
In your code you use DateComponents and all the fields are optional, like e.g. difference.hour. You're using ! before to extract the value to compare it, but it is not a good way as it crashes the app if the value isn't there.
What you should do is like this:
guard let hour = difference.hour,
let minute = difference.minute, [...] else { return cell }
// below code using hour as not optional
in the method for every optional value to safely unwrap it.

In Swift 3 all date components are optionals but you can safely unwrap all optionals which are specified in dateComponents(from:to:
I recommend to use local variables:
let difference = Calendar.current.dateComponents([.second, .minute, .hour, .day, .weekOfMonth], from: from, to: now)
let diffSec = difference.second!
let diffMin = difference.minute!
let diffHour = difference.hour!
let diffDay = difference.day!
let diffWeekOfMonth = difference.weekOfMonth!
if diffSec <= 0 {
cell.postDate.text! = "now"
}
if diffSec > 0 && diffMin == 0 {
cell.postDate.text! = "\(diffSec)s." // 12s.
}
if diffMin > 0 && diffHour == 0 {
cell.postDate.text! = "\(diffMin)m."
}
if diffHour > 0 && diffDay == 0 {
cell.postDate.text! = "\(diffHour)h."
}
if diffDay > 0 && diffWeekOfMonth == 0 {
cell.postDate.text! = "\(diffDay)d."
}
if diffWeekOfMonth > 0 {
cell.postDate.text! = "\(diffWeekOfMonth)w."
}
Nevertheless take a look at DateComponentsFormatter

Related

Label intValue not show for greater than (>) to work

I am new at Swift the code builds just fine but the greater than (>) dose not work. I'm trying to producing at a number in the "totalCoal" label, but never goes over the "coalPileHolding" Second label. I know that this code can be way better But i am trying to get the basic first. I also know that the timeDiffernt ">" dose not work also so somehow I am missing something. Thank you for your help
#IBOutlet weak var coalPileHoldingLabel: UILabel!
func loadBigCoalPile () {
var coalPileHolding = Int ()
if UserDefaults.standard.object(forKey: "coalPileResearch") == nil {
coalPileHolding = 0 } else {
coalPileHolding = UserDefaults.standard.object(forKey: "coalPileResearch") as! Int}
if coalPileHolding == 1 {
let coalPileHolding = 200
coalPileHoldingLabel.text = String(coalPileHolding) }
if coalPileHolding == 2 {
let coalPileHolding = 300
coalPileHoldingLabel.text = String(coalPileHolding) }
if coalPileHolding == 3 {
let coalPileHolding = 400
coalPileHoldingLabel.text = String(coalPileHolding) }
#objc func buttonIsInAction(){
}
#IBOutlet weak var coalRunButton: UIButton!
#IBAction func coalRunButton(_ sender: Any) {
func getMillisecondsNow() -> Int64{
let currentDate = Date()
return getMillisecondsFromDate(date: currentDate)
}
func getMillisecondsFromDate(date: Date) -> Int64{
var d : Int64 = 0
let interval = date.timeIntervalSince1970
d = Int64(interval * 1000)
return d
}
func getTimeDifferenceFromNowInMilliseconds(time: Int64) -> Int64{
let now = getMillisecondsNow()
let diff: Int64 = now - time
return diff
}
var terminationTime = Int64()
if UserDefaults.standard.object(forKey: "latestTerminationDate") == nil {
terminationTime = getMillisecondsNow()
UserDefaults.standard.set(terminationTime, forKey:"latestTerminationDate")
}
else {
terminationTime = UserDefaults.standard.object(forKey: "latestTerminationDate") as! Int64 }
let timeDiff = getTimeDifferenceFromNowInMilliseconds(time: terminationTime)
let timeDiffernt = Int(timeDiff)
let now = getMillisecondsNow()
UserDefaults.standard.set (now, forKey: "latestTerminationDate")
if timeDiffernt > 86400000 { _ = 86400000}
var methodOfCut = Int ()
var machineryButton = Int ()
var qualityOfWorkers = Int ()
if UserDefaults.standard.object(forKey: "methodOfCut") == nil {
methodOfCut = 0 } else {
methodOfCut = UserDefaults.standard.object(forKey: "methodOfCut") as! Int}
if UserDefaults.standard.object(forKey: "machineryButton") == nil {
machineryButton = 0 } else {
machineryButton = UserDefaults.standard.object(forKey: "machineryButton") as! Int}
if UserDefaults.standard.object(forKey: "qualityOfWorkers") == nil {
qualityOfWorkers = 0 } else {
qualityOfWorkers = UserDefaults.standard.object(forKey: "qualityOfWorkers") as! Int}
let coalMayham = (machineryButton) + (qualityOfWorkers) + (methodOfCut)
let (dailyCoalAccumulate) = ((timeDiffernt) * (coalMayham) + 1) / 10000
var coalPileHolding2 = 0
if let coalPile = Int(coalPileLabel.text!) {
let totalCoal = (dailyCoalAccumulate) + coalPile
coalPileHolding2 = Int(coalPileHoldingLabel.text!) ?? 0
if totalCoal > coalPileHolding2 { coalPileHolding2 = totalCoal }
coalPileLabel.text = String(totalCoal)
UserDefaults.standard.set(totalCoal, forKey:"totalCoal")}
callOutLabel.text = String(dailyCoalAccumulate)}}
That mix of numeric types (Int32, Float, Int) is rather confusing. In general you want to use Int or Double. All other variants should only be used when absolutely necessary, for example if an API requires a different type. So lets assume that dailyCoalAccumulate is Int and switch everything else to Int too:
let coalPileHolding = 0
if let coalPile = Int(coalPileLabel.text!) {
let totalCoal = dailyCoalAccumulate + coalPile
let coalPileHolding = Int((coalPileHoldingLabel.text as! NSString).intValue)
if totalCoal > coalPileHolding {
let coalPileHolding = totalCoal
}
coalPileLabel.text = String(totalCoal)
UserDefaults.standard.set(totalCoal, forKey:"totalCoal")
}
callOutLabel.text = String(dailyCoalAccumulate)
Here the intValue API of NSString returns Int32 but I immediately convert it to a regular Int. But of course there is a better way to do this without having to bridge to the Objective-C NSString. If the string doesn't contain a number intValue simply returns zero. We can produce the same behavior when we use the Int initializer to convert the string and then replace the nil value with zero: Int(coalPileHoldingLabel.text!) ?? 0.
Then we have three different variables named coalPileHolding. Since they are defined in different scopes they can share the same name, but are still different variables. My guess is that you want to actually update the coalPileHolding variable. Otherwise the assignment in the inner if makes no sense - the compiler even warns about that.
So lets change coalPileHolding to var and update its value.
var coalPileHolding = 0
if let coalPile = Int(coalPileLabel.text!) {
let totalCoal = dailyCoalAccumulate + coalPile
coalPileHolding = Int(coalPileHoldingLabel.text!) ?? 0
if totalCoal > coalPileHolding {
coalPileHolding = totalCoal
}
coalPileLabel.text = String(totalCoal)
UserDefaults.standard.set(totalCoal, forKey:"totalCoal")
}
callOutLabel.text = String(dailyCoalAccumulate)

How to separate values from an array using Swift 4

How to separate values from an array using Swift 4. Following are my data:
arrWeekly == (
{
date = "2018-04-30";
units = "g/dL";
value = 12;
},
{
date = "2017-06-27";
units = "g/dL";
value = "14.5";
}
)
My Code:
if let arrMonthly = dictPeriod["monthly"] as? [Any], arrMonthly.count > 0
{
self.arrMonth = NSMutableArray(array: arrMonthly)
print("arrMonthly == ",self.arrMonth)
}else{
self.arrMonth = NSMutableArray()
}
I want to separate both dates & Values.
if let arrMonthly = dictPeriod["monthly"] as? [[AnyHasahble:String]], ! arrMonthly.isEmpty {
for disc in arrMonthly{
if let date = disc["date"] as? String{
}
if let units = disc["units"] as? String{
}
if let value = disc["value"] as? String{
}
}
}else{
}
let dictPeriod = YOUR_DICTIONARY
guard let arrMonthly = dictPeriod["monthly"] as? [[String: Any]], !arrMonthly.isEmpty else { return }
let dateArr = arrMonthly.map({ $0["date"] as! String })
let unitsArr = arrMonthly.map({ $0["units"] as! String })
let valueArr = arrMonthly.map({ $0["value"] as! String })

Swift - some mp3 file metadata return nil

I have code like below. For some file I got metadata like artist, title and other without any problem. For other files metadata list is nil but when I check metadata in editor like Tagger - title and other metadata exists. Furthermore when I change metadata in external editor for at least one key - my code starts work properly.
Could someone explain me where I make mistake ?
static func getBookInCatalog(url: URL) -> Book {
let book = Book(url: url)
let isDir: ObjCBool = false
var directoryContents = [URL]()
var totalTime: CMTime?
var size: UInt64 = 0
var chapters:Int = 0
do {
directoryContents = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: [])
} catch let error as NSError {
print(error.localizedDescription)
return book
}
for item in directoryContents {
if !isDir.boolValue {
let result = appDelegate.fileTypes.filter { $0==item.pathExtension.lowercased() }
if !result.isEmpty {
chapters += 1
let fileSize = (try! FileManager.default.attributesOfItem(atPath: item.path)[FileAttributeKey.size] as! NSNumber).uint64Value
size += fileSize
let playerItem = AVPlayerItem(url: item)
let metadataList = playerItem.asset.commonMetadata
let asset = AVURLAsset(url: item, options: nil)
let audioDuration = asset.duration
if let _ = totalTime {
totalTime = totalTime! + audioDuration
} else {
totalTime = audioDuration
}
for metadata in metadataList {
guard let key = metadata.commonKey, let value = metadata.value else{
continue
}
switch key {
case "albumName":
if book.title == nil || book.title == "" {
book.title = (value as? String)!
}
case "artist":
if book.author == nil || book.author == "" {
book.author = (value as? String)!
}
case "artwork" where value is NSData:
if book.image == nil {
book.image = UIImage(data: (value as! NSData) as Data)
}
default:
continue
}
}
}
}
}
if let imageInsideCatalog = getImageFromFolder(url: url){
book.image = imageInsideCatalog
}
if book.title == nil {
book.title = url.deletingPathExtension().lastPathComponent
}
book.chapters = chapters
book.totalTime = totalTime
book.size = size
return book
}
MP3 meta data "standards" have gone through several major iterations over the years (see http://id3.org) . Your editor may be able to read older formats (that AVURLAsset may not support) and save them using the latest/current standard which would make them compatible after any change.

Crash due to optional string in swift 3.0

I was converting the timestamp to time but my timeStampToDate is giving this output "Optional(1476775542548)" due to which it crashes.So how i can remove this Optional string.
let timeStampToDate = (String(describing:merchant.post["timestamp"])) as String
let timeSt = Date(jsonDate:"/Date(\(timeStampToDate))/")
merchantOpenLbl.text = Date().onlyTimee(date: timeSt!)
init?(jsonDate: String) {
// "/Date(1487058855745)/"
let prefix = "/Date("
let suffix = ")/"
let scanner = Scanner(string: jsonDate)
// Check prefix:
guard scanner.scanString(prefix, into: nil) else { return nil }
// Read milliseconds part:
var milliseconds : Int64 = 0
guard scanner.scanInt64(&milliseconds) else { return nil }
// Milliseconds to seconds:
var timeStamp = TimeInterval(milliseconds)/1000.0
// Read optional timezone part:
var timeZoneOffset : Int = 0
if scanner.scanInt(&timeZoneOffset) {
let hours = timeZoneOffset / 100
let minutes = timeZoneOffset % 100
// Adjust timestamp according to timezone:
timeStamp += TimeInterval(3600 * hours + 60 * minutes)
}
// Check suffix:
guard scanner.scanString(suffix, into: nil) else { return nil }
// Success! Create NSDate and return.
self.init(timeIntervalSince1970: timeStamp)
}
Wrapped the optional value that you getting from merchant.post["timestamp"].
if let timeStampToDate = merchant.post["timestamp"] as? String {
print(timeStampToDate)
let timeSt = Date(jsonDate:"/Date(\(timeStampToDate)))/")
merchantOpenLbl.text = Date().onlyTimee(date: timeSt!)
}
Note: If it is still not works then you need to show us declaration of Date(jsonDate:)
Edit: If it is not string then try like this way
if let timeStampToDate = merchant.post["timestamp"] {
print(timeStampToDate)
let timeSt = Date(jsonDate:"/Date(\(timeStampToDate)))/")
merchantOpenLbl.text = Date().onlyTimee(date: timeSt!)
}
You can use guard let to wrap the optional value. Replace your code with below code.
guard let timeStampToDate = merchant.post["timestamp"] as? String else {
return
}
let timeSt = Date(jsonDate:"/Date(\(timeStampToDate))/")
merchantOpenLbl.text = Date().onlyTimee(date: timeSt!)
let timeStampToDate = (String(describing:merchant.post["timestamp"])) as String
let timeSt = Date(jsonDate:"/Date(\(timeStampToDate!))/")
merchantOpenLbl.text = Date().onlyTimee(date: timeSt!)
Edit
if let timeStampToDate = (String(describing:merchant.post["timestamp"])) as? String {
let timeSt = Date(jsonDate:"/Date(\(timeStampToDate))/")
merchantOpenLbl.text = Date().onlyTimee(date: timeSt!)
}

How do I change data model?

I'm making an social media apps.
user
- displayname
- username
- profileImg
- password
- email
comments
- username
- comment
- to
friends
- follower
- following
hashtags
- hashtag
- to
- by
- comment
likes
- to
- by
posts
- postImg
- username
- title
- uuid
My question is when USERS post the image with title text then
I want retrieve username, profileImg, title, comment, commentby, postImg, count of likes
My approach is redesign the posts db
posts
- postImg
- username
- title
- uuid
- comment
- commentby
- profileImg
- count of likes
But I think it is poor design of db.
func loadPosts() {
//STEP 1. Find posts related to people who we are following
let followQuery = PFQuery(className: “friends")
followQuery.whereKey(“following", equalTo: PFUser.current()!.username!)
followQuery.findObjectsInBackground (block: { (objects:[PFObject]?, error:Error?) -> Void in
if error == nil {
//clean up
self.followArray.removeAll(keepingCapacity: false)
//Appending where people following..
//find related objects
for object in objects! {
self.followArray.append(object.object(forKey: “following") as! String)
}
//append current user to see own posts in feed
self.followArray.append(PFUser.current()!.username!)
//STEP 2. Find posts made by people appended to followArray
let query = PFQuery(className: "posts")
query.whereKey("username", containedIn: self.followArray)
query.limit = self.page
query.addDescendingOrder("createdAt")
query.findObjectsInBackground(block: { (objects:[PFObject]?, error:Error?) -> Void in
if error == nil {
//clean up
self.usernameArray.removeAll(keepingCapacity: false)
// self.profileArray.removeAll(keepCapacity: false)
self.dateArray.removeAll(keepingCapacity: false)
self.postArray.removeAll(keepingCapacity: false)
self.descriptionArray.removeAll(keepingCapacity: false)
self.uuidArray.removeAll(keepingCapacity: false)
self.commentsArray.removeAll(keepingCapacity: false)
self.commentsByArray.removeAll(keepingCapacity: false)
//find related objects
for object in objects! {
self.usernameArray.append(object.object(forKey: "username") as! String)
// self.profileArray.append(object.objectForKey("profileImg") as! PFFile)
self.dateArray.append(object.createdAt)
self.postArray.append(object.object(forKey: "postImg") as! PFFile)
self.descriptionArray.append(object.object(forKey: "title") as! String)
self.uuidArray.append(object.object(forKey: "uuid") as! String)
//set Comments
let comment = object.object(forKey: "comment") as! String
let by = object.object(forKey: "commentby") as! String
let commentString = " " + comment
self.commentsByArray.append(by)
self.commentsArray.append(commentString)
}
//reload tableView & end spinning of refresher
self.tableView.reloadData()
self.refresher.endRefreshing()
} else {
print(error!.localizedDescription)
}
})
} else {
print(error!.localizedDescription)
}
})
}
defined cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//define cell
let cell = tableView.dequeueReusableCell(withIdentifier: "ShopDetailCell", for: indexPath) as! ShopDetailCell
cell.userNameLabel.text = usernameArray[(indexPath as NSIndexPath).row - 1]
cell.userNameLabel.sizeToFit()
cell.uuidLabel.text = uuidArray[(indexPath as NSIndexPath).row - 1]
cell.descriptionLabel.text = descriptionArray[indexPath.row - 1]
cell.descriptionLabel.sizeToFit()
cell.commentLabel.sizeToFit()
//Load ProfileImage
let profileImgQuery = PFQuery(className: "_User")
profileImgQuery.whereKey("username", equalTo: usernameArray[(indexPath as NSIndexPath).row - 1])
profileImgQuery.findObjectsInBackground(block: {(objects:[PFObject]?, error:Error?) -> Void in
if error == nil {
//shown wrong user
if objects!.isEmpty {
print("Wrong User")
}
//find related to user information
for object in objects! {
//Set Image
let profilePictureObject = object.object(forKey: "profileImg") as? PFFile
profilePictureObject?.getDataInBackground { (imageData:Data?, error:Error?) -> Void in
if(imageData != nil)
{
let profileURL : URL = URL(string: profilePictureObject!.url!)!
cell.userImg.sd_setImage(with: profileURL, placeholderImage: UIImage(named: "holderImg"))
}
}
}
} else {
print(error?.localizedDescription)
}
})
//Clip to circle
cell.userImg.layoutIfNeeded()
cell.userImg.layer.cornerRadius = cell.userImg.frame.size.width/2
cell.userImg.clipsToBounds = true
// place post picture using the sdwebimage
let postURL : URL = URL(string: postArray[(indexPath as NSIndexPath).row - 1].url!)!
cell.postImg.sd_setImage(with: postURL, placeholderImage: UIImage(named: "holderImg"))
//Calculate post date
let from = dateArray[(indexPath as NSIndexPath).row - 1]
let now = Date()
let components : NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfMonth]
let difference = (Calendar.current as NSCalendar).components(components, from: from!, to: now, options: [])
// logic what to show : Seconds, minutes, hours, days, or weeks
if difference.second! <= 0 {
cell.dateLabel.text = "NOW"
}
if difference.second! > 0 && difference.minute! == 0 {
cell.dateLabel.text = "\(difference.second!) SEC AGO"
}
if difference.minute! > 0 && difference.hour! == 0 {
cell.dateLabel.text = "\(difference.minute!) MIN AGO"
}
if difference.hour! > 0 && difference.day! == 0 {
cell.dateLabel.text = "\(difference.hour!) HR AGO"
}
if difference.day! > 0 && difference.weekOfMonth! == 0 {
cell.dateLabel.text = "\(difference.day!) DAY AGO"
}
if difference.weekOfMonth! > 0 {
cell.dateLabel.text = "\(difference.weekOfMonth!) WEEK AGO"
}
cell.dateLabel.sizeToFit()
//Set Text Label
if cell.descriptionLabel.text!.isEmpty == true || cell.descriptionLabel.text == " "{
if cell.commentLabel.text!.isEmpty == true || cell.commentLabel.text == " "{
cell.dateTop.constant = 7
}else {
cell.dateTop.constant = cell.commentTop.constant + cell.commentLabel.frame.height + 8
}
}else {
if cell.commentLabel.text!.isEmpty == true || cell.commentLabel.text == " "{
cell.dateTop.constant = cell.descriptionTop.constant + cell.descriptionLabel.frame.height + 8
}else {
cell.commentTop.constant = cell.descriptionTop.constant + cell.descriptionLabel.frame.height + 8
cell.dateTop.constant = cell.commentTop.constant + cell.commentLabel.frame.height + 8
}
}
// manipulate like button depending on did user like it or not
let didLike = PFQuery(className: "likes")
didLike.whereKey("by", equalTo: PFUser.current()!.username!)
didLike.whereKey("to", equalTo: cell.uuidLabel.text!)
didLike.countObjectsInBackground(block: {(count:Int32, error:Error?) -> Void in
//if no any likes are found, else found likes
if count==0 {
cell.likeBtn.setTitle("unlike", for: UIControlState())
cell.likeBtn.setImage(UIImage(named:"heartBtn"), for: UIControlState())
}else{
cell.likeBtn.setTitle("like", for: UIControlState())
cell.likeBtn.setImage(UIImage(named: "heartTapBtn"), for: UIControlState())
}
})
//count total likes of shown post
let countLikes = PFQuery(className: "likes")
countLikes.whereKey("to", equalTo: cell.uuidLabel.text!)
countLikes.countObjectsInBackground(block: {(count:Int32, error:Error?) -> Void in
cell.likesLabel.text="\(count) likes"
})
cell.userNameLabel.layer.setValue(indexPath, forKey: "index")
cell.commentBtn.layer.setValue(indexPath, forKey: "index")
cell.moreBtn.layer.setValue(indexPath, forKey: "index")
return cell
}
Could you anyone advising me?
I had read this tutorial "https://parse.com/tutorials/anypic" but I can't decided which data model is better for me
I wish to uses join or pointer method.
You can save the currentUser as a pointer in your Posts class whenever a user makes a post.
note: I will demonstrate in Objective-C but it's very easy for you to translate into Swift. But if you have trouble reading objc code, I will edit my answer to Swift version.
func post { //make a post
var post = PFObject(className:"Posts")
post["user"] = PFUser.current()//save the current user as a pointer pointing to the User class. You can add a column of type pointer in your parse dashboard inside your Posts class.
//set up other attributes here...
post.saveInBackground()
}
Then when we do the query, we can use includeKey to include the user pointer.
let query = PFQuery(className: "posts")
query.whereKey("username", containedIn: self.followArray)
query.includeKey("user")// THIS IS IMPORTANT
query.limit = self.page
query.addDescendingOrder("createdAt")
query.findObjectsInBackground(block: { (objects:[PFObject]?, error:Error?) -> Void in
if !error {
//we can access the user pointer by doing:
for object in objects {
var user = object["user"]
var username = user.username
var profileImage = user["profileImg"] //a PFFile
//...
}
}
Besides, you can always use a PFQueryTableViewController to load the objects for you, so you don't need to store the query results manually.