Unable to update imagefile column in Parse using Swift - 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")
}

Related

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...

Use Facebook profile picture as you profile picture Swift

I am getting facebook's profile picture and displaying it as the profile picture in my app. Here is the code.
if let user = FIRAuth.auth()?.currentUser{
let photoUrl = user.photoURL
let name = user.displayName
self.FacebookUser.text = name
let storage = FIRStorage.storage()
//refer your particular storage service
let storageRef = storage.reference(forURL: "gs://gsignme-14416.appspot.com")
let profilePicRef = storageRef.child(user.uid+"/profile_pic.jpg")
profilePicRef.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) -> Void in
if (error == nil){
self.FacebookPic.image = UIImage(data: data!)
}else{
print("Error downloading image:" )
}
})
if(self.FacebookPic.image == nil)
{
var profilePic = FBSDKGraphRequest(graphPath: "me/picture", parameters: ["height": 300, "width": 300, "redirect": false], httpMethod: "GET")
profilePic?.start(completionHandler: {(_ connection, result, error) -> Void in
// Handle the result
if error == nil {
if let dictionary = result as? [String: Any],
let data = dictionary["data"] as? [String:Any],
let urlPic = data["url"] as? String{
if let imageData = NSData(contentsOf: NSURL(string: urlPic)!as URL){
let uploadTask = profilePicRef.put(imageData as Data, metadata: nil) {
metadata, error in
if (error == nil)
{
let downloadurl = metadata!.downloadURL
}
else
{
print("Error in downloading image")
}
}
self.FacebookPic.image = UIImage(data: imageData as Data)
}}}})}
}else{
}
//The END of the Facebook user and picture code
I was able to get it working for a couple days and now it doesn't work anymore, I have gone through it line by line and I honestly can't figure out why it is not working.
I used this code:
func pictureFromFirebase(loginMethod: Int)
{
if loginMethod == 0 //FB
{
var profilePic = FBSDKGraphRequest(graphPath: "me/picture", parameters: ["height":300, "width":300, "redirect":false], httpMethod: "GET")
let profilePicRef = storageRef.child((user?.uid)!+"/profile_pic.jpg")
profilePicRef.data(withMaxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
// Uh-oh, an error occurred!
// but we don't need to do anything yet. Try to download the profile pic
}
if (data != nil)
{
print("no need to download image from facebook")
self.profileImage.image = UIImage (data: data!)
}
else
{
// THIS IS THE BLOCK THAT HAS BEEN MOVED
// WHICH WILL NOW BE EXECUTED IN TWO CONDITIONS -
// 1. AN ERROR IN THE DOWNLOAD
// 2. NO PROFILE PIC AVAILABLE
print("downloading image from facebook")
profilePic?.start(completionHandler: {(_ connection, _ result, _ error) -> Void in
if (error == nil)
{
if let dictionary = result as? [String:Any], let data = dictionary["data"] as? [String:Any],
let urlPic = data["url"] as? String {
if let imageData = NSData(contentsOf: NSURL(string: urlPic)! as URL)
{
let uploadTask = profilePicRef.put(imageData as Data, metadata: nil){
metadata, error in
if (error == nil)
{
let downloadUrl = metadata!.downloadURL
}
else
{
print("error in downloading image")
}
}
self.profileImage.image = UIImage(data: imageData as Data)
}
}
}
})
}
}
}
}
from this post Second If statement gets called before first statement finished in one function and it worked
you just get your facebook profile pic. using this url and put the url in your UIImageview
let profilepicURl = "https://graph.facebook.com/\(user_id_fb)/picture?type=large" //user_id_fb like 1251246454544 your facebook ID

Get data from User table without current user

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

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)
}
})
}

Get data from Parse.com to swift

In my code it receives the images from parse, and show it in a imageView. Here is the code:
http://pastebin.com/kDjAgPRT
If needed, here is my code for upload:
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_image2.png", data: imageData)
//var parseImageFile = PFFile(data: imageData)
posts["imageFile"] = parseImageFile
posts.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if error == nil{
// Take user home
println(success)
println("Data uploaded")
}
else{
println(error)
}
})
}
else{
println(error)
}
})
}
}
As you can see, here is my Parse inside "Posts":
How can i also get "imageText", "uploader" and "createdAt" for the images? Like instagram has.
Try this:
struct Details {
var username:String!
var text:String!
var CreatedAt:NSDate!
var image:UIImage!
init(username:String,text:String,CreatedAt:NSDate,image:UIImage){
self.username = username
self.text = text
self.CreatedAt = CreatedAt
self.image = image
}
}
func QueryImagesFromParse(){
var arrayOfDetails = [Details]()
var query = PFQuery(className: "Posts")
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil
{
if let newObjects = objects as? [PFObject] {
for oneobject in newObjects {
var text = oneobject["imageText"] as! String
var username = oneobject["uploader"] as! String
var time = oneobject.createdAt
var userImageFile = oneobject["imageFile"] as! PFFile
userImageFile.getDataInBackgroundWithBlock({ (imageData:NSData?, error:NSError?) -> Void in
if error == nil {
let newImage = UIImage(data: imageData!)
var OneBigObject = Details(username: username, text: text, CreatedAt: time!, image: newImage!)
arrayOfDetails.append(OneBigObject)
// then reloadData
}
})
}
}
}
}
}
SO NOW with the arrayOfDetails you could populate your cells...