Get data from User table without current user - swift

I'm trying to get all the user's from the _User table and get their images and put them into an array. The below code works when I am logged in (current user != nil)
but when I'm not logged in (current user = nil) I get no images at all
How can i achive this query without being a current user ???
I have the following function
let chefUserQuery = PFQuery(className: "_User")
chefUserQuery .whereKey("chef", equalTo: true)
chefUserQuery .findObjectsInBackgroundWithBlock{
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFUser] {
var ai = 0
for object in objects {
print("kati")
let imageChef = object["avatar"] as! PFFile
imageChef.getDataInBackgroundWithBlock({ (data, error) -> Void in
if error == nil {
if let imageData = data {
let imagatzaki = UIImage(data: imageData)
let idChef = object.objectId
self.imagesOfChef[ai] = chefImages(objidChef: idChef, imageChef: imagatzaki)
ai += 1
print(self.imagesOfChef)
} } })
}
completion(.Success())
}
}
else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
Thanks

Related

Use of Unresolved Identifier firebase function

I've defined the function sendDataToDatabase but for some reason it's not resolving photoUrl?
I've been trying to figure out what might be causing this for 6 hours now and can't seem to find a solution, if anyone could provide some help it would be appreciated.
#IBAction func shareButton_TouchUpInside(_ sender: Any) {
ProgressHUD.show("Waiting...", interaction: false)
if let profileImg = self.selectedImage, let imageData = profileImg.jpegData(compressionQuality: 0.1) {
let photoId = NSUUID().uuidString
let storageRef = Storage.storage().reference(forURL: "manifest-bit-233115.appspot.com").child("posts").child(photoId)
storageRef.putData(imageData, metadata: nil, completion: { (metadata, Error) in
if Error != nil {
return
}
storageRef.downloadURL(completion: { (URL, Error) -> Void in
if (Error != nil) {
//handle any errors
} else {
//get download url
let photoUrl = URL?.absoluteString
}
self.sendDataToDatabase(photoUrl: photoUrl!)
})
}
)}
func sendDataToDatabase(photoUrl: photoUrl!) {
let ref = Database.database().reference()
//let uid = Auth.auth().currentUser!.uid
let postsRef = ref.child("posts")
let newPostId = postsRef.childByAutoId().key
let newPostRef = postsRef.child(newPostId!)
newPostRef.setValue(["photoUrl": photoUrl])
}
There are many issues.
You have to call sendDataToDatabase only in the else branch and declare the parameters with starting lowercase letters.
The parameters are not types.
storageRef.downloadURL(completion: { (url, error) -> Void in
if let error = error {
//handle any errors
} else {
//get download url
let photoUrl = url!.absoluteString
self.sendDataToDatabase(photoUrl: photoUrl)
}
})
and you have to declare the type in the function
func sendDataToDatabase(photoUrl: String) { ...
This won't work:
storageRef.downloadURL(completion: { (URL, Error) -> Void in
if (Error != nil) {
//handle any errors
} else {
//get download url
let photoUrl = URL?.absoluteString
}
self.sendDataToDatabase(photoUrl: photoUrl!)
})
photoUrl will only be available within the else clause, since that's where it's defined, and you can not use it outside of that scope.
Also, this:
func sendDataToDatabase(photoUrl: photoUrl!)
should probably be:
func sendDataToDatabase(photoUrl: String)
It's also a good idea to not name variables URL and Error, since they are identical to the URL and Error classes. Name them url and error instead.

Parse/Image not loads the image from the server?

Tell me how to get rid of the error in my method? has many options tried and still the image does not display on ViewContoller.
func detailObject() {
let query = PFQuery(className: "soccer")
query.findObjectsInBackground { (objects:[PFObject]?, error:Error?) in
if error == nil {
for objects in objects! {
let detailPrognozS = objects["detailPrognozS"] as! String
let detailTitleS = objects["detailTitleS"] as! String
let detailTextS = objects["detailTextS"] as! String
let imageDetail = objects["detailImageS"] as? PFFile
DispatchQueue.main.async { [unowned self] in
self.prognozDetail.text = detailPrognozS
self.textView.text = detailTextS
self.titleDetail.text = detailTitleS
}
imageDetail?.getDataInBackground(block: { (data:Data?, error:Error?) in
if error == nil {
if let imageData = data {
DispatchQueue.main.async { [unowned self] in
self.imageDetail.image = UIImage(data: imageData)
}
}
}
})
}
}
}
The code displays this error:
Fatal error: unexpectedly found nil while unwrapping an Optional value Error be in this line"self.imageDetail.image = UIImage(data: imageData)" and the app crashes...please tell me.I beg you...

Unable to update imagefile column in Parse using Swift

I am selecting a cell in table view, passing value to view controller and then allow user to update the row on Parse (running on Heroku) using below code.
Issue i am facing is - "title" column is updated but imagefile column doesnt get updated with new image selected. I can see that new image is indeed passed into the code.
I am using synchronous call because dont want user to move ahead unless record is saved.
what could be wrong? Same code to save a new object works fine.
Thanks
Ashish
let query = PFQuery(className:"class")
query.whereKey("objectId", containsString: passedObject.objectId)
do {
let results = try query.findObjects()
if results.count == 0 {
print("error")
success = false
} else {
//update
do {
let obj = results.first
obj!["title"] = Title.text!
let imageData = UIImageJPEGRepresentation(imageOutlet.image!,0.2)
let imageFile = PFFile(name: "image.png", data: imageData!)
//try imageFile?.save() // is this needed?
obj!["imagefile"] = imageFile
try obj!.save()
self.success = true
} catch let er as NSError {
print(" error while updating - \(er)")
}
}
} catch {
print("error while querying \(error)")
success = false
}
I ran some tests on my side and this code works for me:
Aync Version
let query = PFQuery(className: "FileTest")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
let imageData = UIImageJPEGRepresentation(self.imageOutlet.image!, 0.2)
let fileToSave = PFFile(name: "myfile.png", data: imageData!)
let firstObj = objects?.first
firstObj!["fileToSave"] = fileToSave
firstObj!.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
print("Object has been saved.")
}
}
Sync Version
let query = PFQuery(className: "FileTest")
do {
let objects = try query.findObjects()
let firstObj = objects.first
let imageData = UIImageJPEGRepresentation(self.imageOutlet.image!, 0.2)
let fileToSave = PFFile(name: "myfile.png", data: imageData!)
firstObj!["fileToSave2"] = fileToSave
try firstObj!.save()
print("object saved")
} catch let er as NSError {
print("error")
}

In Swift, how do you check if pointer in Parse column is empty or not

Within my user object I added a column to add a users favorite team. The column is identified as favTeam and is a pointer to a teams class
Here is my code. I have populated my user with a favorite team however the logic is always showing that "favteam nil"
if let object = PFUser.currentUser()!["favTeam"] as? [PFObject]{
print("favteam not nil")
print(object)
let favTeam = PFUser.currentUser()!["favTeam"]
favTeamText.text = favTeam["Name"] as? String
if let favTeamImageView = favTeam["teamLogo"] as? PFFile {
favTeamImageView.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
self.teamLogo.image = UIImage(data: imageData)
}
}
}
}
}
else {
print("favteam nil")
}
I can accomplish this by using a PFUser.query() as follows...
func fetchFavoriteTeam() {
let userQuery: PFQuery = PFUser.query()!
userQuery.whereKey("username", equalTo: (currentUser?.username)!)
userQuery.findObjectsInBackgroundWithBlock({
(users, error) -> Void in
var favTeam = users!
if error == nil {
if favTeam != nil {
favTeamContainer = favTeam.valueForKey("favTeam") as! PFObject
}
} else {
print(error)
}
})
}

Loading images from parse.com

This is my saving image to parse:
func uploadPost(){
var imageText = self.imageText.text
if (imageView.image == nil){
println("No image uploaded")
}
else{
var posts = PFObject(className: "Posts")
posts["imageText"] = imageText
posts["uploader"] = PFUser.currentUser()
posts.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if error == nil{
//**Success saving, now save image.**//
// Create an image data
var imageData = UIImagePNGRepresentation(self.imageView.image)
// Create a parse file to store in cloud
var parseImageFile = PFFile(name: "upload_image.png", data: imageData)
posts["imageFile"] = parseImageFile
posts.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if error == nil{
// Take user home
println("Data uploaded")
}
else{
println(error)
}
})
}
else{
println(error)
}
})
}
}
How can I load the images from parse? This is how my Parse.com "Posts" data looks like:
Any suggestions?
I think maybe something like using this:
self.imageView.sd_setImageWithURL(url, completed: block)
But I donĀ“t know how I get the URL. And what if the images has different names?
try something like this
let imageFile = pfObject["imageFile"] as? PFFile
if imageFile != nil{
imageFile!.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
self.imageView.image = UIImage(data: imageData)!
}
}
}
}
Where pfObject is the reference to your object. There are other ways you could check for a nil value, but this should work.
As long as you have a reference to the correct object (which you can get via a query for objectId) then you should only need the name of the column the image is file is stored in and not the image file itself.