Conditional cast from PFFile toPFFile always succeed - ios

I get a warming of "Conditional cast from PFFile toPFFile always succeed" which highlighted if let tempProductPicture = self.askProductImageArray[0] as? PFFile. What is the best way to solve it? Thanks
var askProductImageArray = [PFFile]()
override func viewDidLoad() {
let query = PFQuery(className: "products")
query.whereKey("title", equalTo: labelTitleText)
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error:NSError?) -> Void in
if error != nil {
}
for object in objects! {
self.askProductImageArray.append(object.objectForKey("detailsImage") as! PFFile)
self.askTable.reloadData()
}
if let tempProductPicture = self.askProductImageArray[0] as? PFFile {
tempProductPicture.getDataInBackgroundWithBlock { data, error in
if data == nil {
} else if error != nil {
} else {
self.productPicture.image = UIImage(data: data!)
}
}
}
}

Your self.askProductImageArray is an array of type PFFIle so there is no need to do as? PFFile because swift is strongly typed language and it will hold only PFFile so remover as? PFFile at the end.
In your case you don't need to do if let at all, you just need to check if item already exist.
you can do something like this
if self.askProductImageArray.count > 0 {
let tempProduct = self.askProductImageArray[0]
// and do rest
}

Related

Parse - Query after a specific row

How can I query after a specific row where the objectId is equal to a objectId I have stored?
This is my query code:
func queryStory(){
let query = PFQuery(className: "myClassStory")
query.whereKey("isPending", equalTo: false)
query.limit = 1000
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (posts: [PFObject]?, error: NSError?) -> Void in
if (error == nil){
// Success fetching objects
for post in posts! {
if let imagefile = post["userFile"] as? PFFile {
self.userFile.append(post["userFile"] as! PFFile)
self.objID.append(post.objectId!)
self.createdAt.append(post.createdAt!)
}
}
print("Done!")
}
else{
print(error)
}
}
}
This is my Parse database class:
What I want, is to only query the items that was createdAt after the objectId: woaVSFn89t. How can I do this?
Try filtering the objects once you have found them:
query.findObjectsInBackgroundWithBlock { (posts: [PFObject]?, error: NSError?) -> Void in
if (error == nil){
// Success fetching objects
var thePostTime = NSDate()
for post in posts! {
if post.objectId == "The Object Id You Were Trying To Find" {
thePostTime = post.createdAt!
}
}
for post in posts! {
if post.createdAt!.isGreaterThan(thePostTime) == true {
if let imagefile = post["userFile"] as? PFFile {
self.userFile.append(post["userFile"] as! PFFile)
self.objID.append(post.objectId!)
self.createdAt.append(post.createdAt!)
}
}
}
print("Done!")
}
else{
print(error)
}
}
You will notice that I compared the dates using this: NSDate Comparison using Swift
Before the for-loop make a variable:
var havePassedObjectId = false
Then inside the for-loop check if the current post is equal to the object id you want:
if post.objectid == "woaVSFn89t" {
self.userFile.append(post["userFile"] as! PFFile)
//Continue appending to arrays where needed
havePassedObjectId = true
} else if havePassedObjectId == true {
self.userFile.append(post["userFile"] as! PFFile)
//Continue appending to arrays where needed
}
This will check if you have already passed the object and append all the objects after.

Downcast from '[PFObject]?' to '[PFObject]' only unwraps optionals

I am saving a parse query to a array but i ket the following error on if let objects = objects as? [PFObject]
And the following error happens Downcast from '[PFObject]?' to '[PFObject]' only unwraps optionals.
any one know how to solve this?
func getArray(funcstring: String){
var userGeoPoint: PFGeoPoint
PFGeoPoint.geoPointForCurrentLocationInBackground {
(geoPoint: PFGeoPoint?, error: NSError?) -> Void in
if error == nil {
userGeoPoint = geoPoint!
}
}
var searchQuery: [String] = [String]()
var query = PFQuery(className:"User")
query.whereKey("geoLocation", nearGeoPoint:userGeoPoint)
query.limit = 100
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
self.searchQuery.append(object.objectForKey("objectId") as! String)
}
}
} else {
print("\(error?.userInfo)")
}
}
}
objects is declared as [PFObject]?.
You're going to downcast the object to something the compiler already knows.
Just check for nil
if let unwrappedObjects = objects {
for object in unwrappedObjects {
self.searchQuery.append(object.objectForKey("objectId") as! String)
}
}
or still "swiftier"
if let unwrappedObjects = objects {
self.searchQuery = unwrappedObjects.map{ $0["objectId"] as! String }
}

GetDataInBackgroundWithBlock | imageData is returning a nil value

So I am saving some objects to the localDatastore using parse.
//Pin the objects here!!
var imageObject = PFObject(className: "img")
imageObject["theFile"] = imageFile
imageObject.pinInBackgroundWithBlock({ (success, error) -> Void in
if error == nil {
imageObject.saveEventually()
println("object pinned in background")
} else {
println(error)
}
})
Then in the viewDidLoad I am querying the objects and appending them into an array of PFFile's
var query = PFQuery(className: "img")
query.fromLocalDatastore()
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil{
var objects : AnyObject = objects as! AnyObject
for object in objects as! [AnyObject]{
self.testImages.append(object["theFile"] as! PFFile)
}
} else {
println(error)
}
}
With this array now containing data. I am trying to insert the images into the tableView
if testImages.count >= 1{
testImages[indexPath.row].getDataInBackgroundWithBlock({ (imageData, error) -> Void in
if error == nil{
//The app crashes here ~ fatal error: unexpectedly found nil while unwrapping an Optional value
cell.theImage.image = UIImage(data: imageData!)
} else {
println(error)
}
})
}
Because you are using a tableview, I think the best way is to download all the images from Parse and save it to an array. Then in the cellForRowAtPath method then you assign each index of that array to the cell.imageView.image
var query = PFQuery(className:"img")
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil
{
if let objects = objects as? [PFObject]
{
for one in objects
{
var pictureImage = one["theFile"] as! PFFile
pictureImage.getDataInBackgroundWithBlock({ (dataToget:NSData?, error:NSError?) -> Void in
if error == nil
{
if let Image = UIImage(data: dataToget)
{
// save the image to array
// reload the tableview
}
}
})
}
}
}
}

How to sort Object Array from a PFQuery?

Hi I have a PFQuery where I am retrieving map images and I need to sort them so that i can retrieve the correct image in my code. This is currently my code:
func retrieveImages() {
self.imageArray = [UIImage]()
var query = PFQuery(className:"Maps")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
self.objectNames.append(object["Name"]!)
let userImageFile = object["imageFile"] as! PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if imageData != nil {
let imageData = imageData
var image = UIImage(data:imageData!)
if image != nil {
self.imageArray.append(image!)
}
}
}
}
}
}
}
}
}
I tried to sort the query by using the orderByDescending function but when i run the code only the names of the objects are sorted and the images themselves are not. There also seems to be no pattern in how the images are sorted because each time I run this code the order of the images are different. Any advice or insight would be appreciated.

Problems When Trying to display images from Parse using Swift

I am trying to display an image from parse using swift. This is my code:
var query = PFQuery(className: "Maps")
query.getObjectInBackgroundWithId("1234asdf3456") {
(object: PFObject?, error: NSError?) -> Void in
if error == nil
{
println(object)
var objectAsPF = object as PFObject!
let file = objectAsPF["imageFile"] as! PFFile
file.getDataInBackgroundWithBlock {
(imageData:NSData?, error:NSError?) -> Void in
if error == nil {
if let imageData = imageData {
let map:UIImage = UIImage(data: imageData)!
self.MapView.image = map
println("success")
}
}
}
}
else
{
println(error)
}
}
I set a breakpoint at println("success") and i checked the variable values and everything is fine until i try to convert imageData to UIImage. Any tips?
Use this code to retrieve images from parse then convert it from a PFFile to a UIImage...
var query = PFQuery(className:"Maps")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
self.scored = objects!.count
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
let userImageFile = object["imageFile"] as! PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
let image = UIImage(data:imageData)
if image != nil {
self.imageArray.append(image!)
}
}
}
}
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
dispatch_async(dispatch_get_main_queue()) {
println("Finished Loading Image")
}

Resources