Load multiple images from specific pointer Id using iOS - ios

I want load all image uisng one id that is pointer.I have 3 class that name is "categories","Ads" and "adimages".The image of class is as.
[][2[]3
I try to implement but can not get any succes.My implement code in xcode is like below
var DetaiId : AnyObject = ""
let query = PFQuery(className:"adImages")
query.whereKey("adIMG", equalTo:DetaiId)
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
self.ImagearrCate = objects!
self.getImageData(objects! as [PFObject])
print(self.ImagearrCate)
//MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
}
else {
print("Error")
print("Error: \(error!) \(error!.userInfo)")
}
}
func getImageData(objects: [PFObject]) {
for object in objects {
let thumbNail = object["image"] as! PFFile
print(thumbNail)
thumbNail.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
if (error == nil) {
let image = UIImage(data:imageData!)
//image object implementation
self.mixPhotoArray.append(image)
print(image)
}
}
}//for - end
}
Here Detailid is get the id from selected row of tableview.That id is passed in wherekey.I get all the image from selected row id.For example in adIMG column i 5 entry for mDjQTYaPMg id.Nut no any image find.
If try to put static id then logcat error is
Error Domain=Parse Code=102 "pointer field adIMG needs a pointer value" UserInfo={code=102, temporary=0, error=pointer

You need to pass pointer value as value of adIMG parameter means you have to create PFObject of Ads class with specific objectId.
Then you have to pass this object as value of adIMG parameter.
See following Code to better understand. May be help you.
let objectAds = PFObject(withoutDataWithClassName:"GameScore", objectId:"xWMyZ4YEGZ")
And then pass like this in PFQuery.
let query = PFQuery(className:"adImages")
query.whereKey("adIMG", equalTo:objectAds)

Related

Append UI Images from array to slideshow swift

I'm trying to make a slideshow with this library
https://github.com/zvonicek/ImageSlideshow
So i'm making a query, i bring some images and i append them here
var sliderArray = [UIImage]()
var testimg:UIImage!
let idaki = recipeObj.objectId
let pointer2 = PFObject(outDataWithClassName:"Recipes", objectId: idaki!)
let galquery = PFQuery(className:"sliderRecipes")
galquery.whereKey("recipe", equalTo: pointer2)
galquery.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects {
for object in objects {
count += 1
let glrimg = object["sliderImage"] as! PFFile
glrimg.getDataInBackgroundWithBlock {
(imageData3: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData2 = imageData3 {
self.testimg = UIImage(data:imageData2)
print(self.testimg)
print(self.sliderArray)
self.sliderArray.append(UIImage(data:imageData2)!)
}
if count == objects.count { print(self.sliderArray) }
}
}
// print("test")
// print(self.sliderPinakas)
}
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
And after all this i DONT have an array with images. In the print above it first shows the empty array and after that it shows the prints of UI Images that i want to show them like this to a slider
slideshow.setImageInputs([ImageSource(image: UIImage(named: "myImage"))!, ImageSource(image: UIImage(named: "myImage2"))!])
but instead of having to do it with the name, UIImage(named: "myImage"))! i would like to do it this way
self.slider.setImageInputs([ImageSource(image: self.testimg)])
for all the images of the array, cause the above line shows only one.
Is there anyone that could help?
Thanks!
You have pass to self.slider.setImageInputs array of all objects ImageSource [ImageSource(image: self.testimg1), ImageSource(image: self.testimg2), ...] etc., not only one object [ImageSource(image: self.testimg)].
If you add images like:
self.slider.setImageInputs([ImageSource(image: self.testimg)])
self.slider.setImageInputs([ImageSource(image: self.testimg2)])
you'll simply replace first image with second.
Create new array, enumerate all images from sliderArray, and append they to array ImageSource(image: self.testimg1) objects.
Also remember, you have to call this from block glrimg.getDataInBackgroundWithBlock!
add before for
var count = 0
and add inside block
count +=1
if count == objects.count {
print(self.sliderArray)
}.
That will print array when all objects finished loads (they can loads in chaotic order).

Query Parse for all the data in a table and placing into array

I am making a running app and would like to have a viewController in which the user has running tips and facts randomly display on the field. I would like to query parse for the objectIds to then reference the id and assign the label the tip or fact. Currently I have hard coded the Ids into the app but I would like that array to contain the results from the query the code is as follows:
func GetObjectID(){
ObjectIDs = ["id1","id2","id3","id4","id5","id6","id7","id8"]
RandomID = Int(arc4random_uniform(UInt32(ObjectIDs.count)))
}
func TheInfo(){
GetObjectID()
var query : PFQuery = PFQuery(className: "FactsandTips")
query.getObjectInBackgroundWithId(ObjectIDs[RandomID]){
(ObjectHolder : PFObject?, error: NSError?) -> Void in
if (error == nil) {
self.fact = ObjectHolder!.valueForKey("Fact") as? String
self.tips = ObjectHolder!.valueForKey("Tips") as? Array
if(self.tips.count > 0){
self.factLabel.text = self.fact
self.Button1.setTitle(self.tips[0], forState: UIControlState.Normal)
self.Button2.setTitle(self.tips[1], forState: UIControlState.Normal)
self.Button3.setTitle(self.tips[2], forState: UIControlState.Normal)
self.Button4.setTitle(self.tips[3], forState: UIControlState.Normal)
}
} else {
print("There is something wrong!")
}
}
}
I am using swift, Xcode7, and parse as my backend
Below is the code I use to query a Parse table, retrieve all results and add it all into an array. I then use the array as the source for a pickerView.
var query:PFQuery = PFQuery(className: "Drivers")
query.addAscendingOrder("Name")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
self.astrDrivers.append(object["Name"]! as! String)
}
}
self.pkvDriverTrack.reloadAllComponents()
} else {
print("Error: \(error) \(error!.userInfo)")
}
}
Note the line self.astrDrivers.append(object["Name"]! as! String). This is adding the Name column of each record to my self.astrDrivers array.
If you wanted to do retrieve multiple columns, your best bet is to create a custom object like below:
class ObjectNewFact:NSObject {
var column1:String = String() // You might want to choose more descriptive variable names (I just don't know what your column names are).
var column2:Int = Int()
// etc.
}
You could then create an array of ObjectNewFacts with a line like
var aFacts:[ObjectNewFact] = [ObjectNewFact]()
Then you could amend your routine to retrieve the data from Parse to:
var query:PFQuery = PFQuery(className: "Drivers")
query.addAscendingOrder("Name")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
var NewFact:ObjectNewFact = ObjectNewFact()
NewFact.column1 = object["Column1"] as! String
NewFact.column2 = object["Column2"] as! Int
self.aFacts.append(NewFact)
}
}
self.pkvDriverTrack.reloadAllComponents()
} else {
print("Error: \(error) \(error!.userInfo)")
}
}
Now you have an array full of facts. You might want to go down this custom object approach because you can also include things like the Fact ID or how many times the fact has been shown (if you're keeping track of that sort of thing). It provides a more flexible solution for any changes in the future.
I hope this helped.

Make a Query with a Pointer in Parse and Swift

I'm trying to make a Query with a Pointer in Parse.
Basically I have two classes "commentsTable" and "_User", I want to get the comment of the user from class "commentsTable" on a determined post, and then get the username and the profile_pic from the class "_User"
_User Class
commentsTable Class
func loadAndShowComments(){
let query2 = PFQuery(className: "commentsTable")
query2.orderByDescending("createdAt")
query2.whereKey("newsColumns", equalTo: printteste!)
query2.includeKey("username")
query2.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if let objects = objects as [PFObject]? {
for object in objects {
print(object["commentColumn"])
}
}
for cardset in objects! {
var lesson = cardset["username"] as! PFObject
var name = lesson["username"] as! String
print("By user: \(name)")
}
I'm able to see the query, I print the result an I have the following output:
This is a post!
This is a test post!
By user: teste#teste.com
By user: mmachado
And in my app I display this informations inside a TableView, I'm successfully can show the results for the Query in the func cellForRowAtIndexPath:
if let usuarioComentario = object?["commentColumn"] as? String {
cell?.usuarioComentario?.text = usuarioComentario
}
But I'm no able to return the values of my other class, _User
I think I misunderstood some concept but at this point I don't know what concept, any ideas?
Thanks.
By using query2.includeKey("username") you are already retrieving all of the User data associated with each commentsTable object.
You can access the related User data using the following.
if let commentUser = object["username"] as? PFUser {
let name = commentUser["username"] as! String
let profilePicture = commentUser["profile_pic"] as! PFFile
}
You need to store the query results to an array for later use if you aren't already. If you are using Parse's provided PFQueryTableViewController this will be handled for you by implementing the queryForTable() method and the results are automatically stored in an array of dictionaries called objects.
It is also worth noting that you will have to still have to load the PFFile because they are not included in query results. You will want to assign the PFFile to a PFImageView and then call loadInBackground. See the example below.
let imageView = PFImageView()
// Set placeholder image
imageView.image = UIImage(named: "placeholder")
// Set remote image
imageView.file = profilePicture
// Once the download completes, the remote image will be displayed
imageView.loadInBackground { (image: UIImage?, error: NSError?) -> Void in
if (error != nil) {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
} else {
println("image loaded")
}
}
Lastly, I'd recommend changing the name of the User pointer within commentsTable from "username" to "user" so there is no confusion with the username field of the user class. Here's a link to a great tutorial which you may also find helpful

Parse.com Query to Get All Items with a Specific Pointer

I want to get all items from my Parse.com table called Sticker, from a particular shop. My Sticker table has a column called shopId. So the obvious solution is this:
//get all stickers from one shop of category dress
var query = PFQuery(className:"Sticker")
query.whereKey("shopId", equalTo: "QjSbyC6k5C")
query.whereKey("category", equalTo: "DR")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
println(object.objectId)
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
However that causes this error:
error: pointer field shopId needs a pointer value
I have seen a common solution for this seems to be to pass the query the actual object and not a string of the ID. Does this mean I have to first do a separate query to get the specific shop object, and then pass that to my query? Or is there a shorter way?
Here is my attempt to get the shop but it's causing this error:
Can only call -[PFObject init] on subclasses conforming to
PFSubclassing
var query1 = PFQuery(className: "Shop")
var shop1 = PFObject()
query1.getObjectInBackgroundWithId("QjSbyC6k5C") {
(shop: PFObject?, error: NSError?) -> Void in
shop1 = shop!
}
EDIT: So my solution was basically doing what the answer suggested. My code was this (Glamour is the name of the shop):
var shopQuery = PFQuery(className:"Shop")
shopQuery.getObjectInBackgroundWithId("QjSbyC6k5C") {
(glamour: PFObject?, error: NSError?) -> Void in
if error == nil && glamour != nil {
println(glamour)
//get all stickers from one shop of category dress
var query = PFQuery(className:"Sticker")
query.whereKey("shopId", equalTo: glamour!)
query.whereKey("category", equalTo: "DR")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
println(object.objectId)
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
} else {
println(error)
}
}
I will leave this question here and maybe someone will answer with a comment: Is there any way to get the shop and give it class scope so that we do not have to nest the second query inside the success of the first query? Would that be more elegant?
You need to pass PFObject. change your code with following
PFObject *object = ...
var query = PFQuery(className:"Sticker")
query.whereKey("shopId", equalTo: "QjSbyC6k5C")
query.whereKey("category", equalTo: object);

Retrieve values out of PFObject

I have a save button to save Score and Playername to GameScore in Parse. When I load the GameScore from Parse I want to set the value that i loaded to the variable "score". This don't work, can anyone please tell me what i am doing wrong?
Thanks
Exapmle: let score = gameScore["score"] as Int
// Load button tapped
#IBAction func loadButtonTapped(sender: UIButton) {
var query = PFQuery(className:"GameScore")
query.getObjectInBackgroundWithId("F1efANYzOE") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil && gameScore != nil {
println(gameScore)
let score = gameScore["score"] as Int
} else {
println(error)
}
}
}
}
Try this following code for retrieving specific data from specific columns. You have to enter your object name, Object ID and column name in the below code and run it. It will work.
let query = PFQuery(className:"Your Object name")
query.getObjectInBackgroundWithId("Your Object ID") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil {
print(gameScore!.objectForKey("your column name") as! String)
} else {
print(error)
}
}

Resources