Does parse PFUser download all User object columns content? - ios

I have a User class in Parse that contains a profilePicture along with some other User info. I couldn't figure out if when I run a query in Swift and Parse returns the PFUser object, does that object already contain the profilePicture or does it download it when I use
PFUser.currentUser()?["profilePicture"]

The object only contain the profilePicture as a PFFile (PFFile representes a file of binary data stored on the Parse servers). You are simply accessing the PFFile which is by indexing with ["profilePicture"].
To get the actual profilePicture when you use it, you can do something like the following to turn the PFFile into UIImage and display it out.
let imageFile = listingObjectPassed["imageFile"] as! PFFile
imageFile.getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
self.imagePic.image = downloadedImage
}
}

Related

How To Properly Update User Profile Image

What is the updated code to upload user profileImage, I got an error trying to update user profileImage.
How do I fix this error?
Cannot invoke initializer for type 'UIImage' with an argument list of
type '(#escaping () -> ())'
self.ProfileImage.image = UIImage{data; data!}
You are using { braces } whereas you need to use ( round brackets )
myImageView.image = UIImage(data: imageData)
There are few issues with your code such as you are using {} instead of () .
So , the code will actually look like ...
self.ProfileImage.image = UIImage(data: data!)
but since data is optional value , it can come as nil if not handled properly. This will lead to crash within your app . So use optional binding in such cases to check whether the data variables actually contain any values , like the code below.
if let imageData = data{
self.ProfileImage.image = UIImage(data: imageData)
}else{
self.ProfileImage.image = UIImage(named : "image_when_no_value_is_present")
}

download Image and save it json using SwiftyJSON

I have json in below format which I am fetching from server and parsing using SwiftyJSON.
{
name: "Ganesh"
imageURL:"www.abc.com/image.png"
}
I am downloading image using below code :
do{
let myData = try Data(contentsOf: url)
}catch{
Print("error")
}
Note: "url" contains url from json which is converted from string to URL
I want to save this "myData" in same json above with different key and access the same in future.
I am trying to save myData in json using SwiftyJSON method :
responseJSON["image"] = try JSON(data: myData)
Error which I am receiving :
"if Error while converting data into json The data couldn’t be read because it isn’t in the correct format."
I am not getting what is the problem?
Image is present at that url. if I convert myData into UIImage and If I assign it on UIImageView I can see it.
If you want to save an image in JSON, the best way would be to convert Data to Base64 string
if let base64encodedString = myData.base64EncodedString(){
responseJSON["image"] = base64encodedString
}
To restore image, try this
guard let base64encodedString = responseJSON["image"] as? String else { return }
guard let imageData = Data(base64Encoded: base64encodedString) else { return }
let image = UIImage(data: imageData)
Although Base64 - encoded images take approximately 33% more space than raw data, they are web and database safe - base64 strings contain neither control characters, nor quotes, and can be transferred as parameter in URL query strings.

Store Parse Files to Amazon S3 using iOS Swift XCode

I have hosted my own Parse Server on Heroku. I am adding files to a Parse table column and want to save to my own S3,
I have followed the guide,
https://github.com/ParsePlatform/parse-server/wiki/Storing-Files-in-AWS-S3
I created my own bucket, created my user, created my policy, attached my policy to my user
Edited my Parse server deployment on Heroku to point to a new filesAdapter
But the following code is still saving the file to MongoDB(GridStore), is there anything else needed to be done to start using my own S3?
let myImage : UIImage = UIImage(named:"bird")!
let imageData: NSData = UIImagePNGRepresentation(myImage)!
let imageFile: PFFile = PFFile(name: "bird.png", data: imageData)!
let pfuser = PFObject(className: "TestObject")
pfuser.setObject("sample text", forKey: "textcol")
pfuser.setObject(imageFile, forKey: "image")
pfuser.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
print("Object has been saved.")
}
Thank you!

Retrieving Parse Images Are Out of Order Swift

I am writing an application in Swift that uses Parse for its backend. The user can post images to parse and they are displayed in a collectionView when the user logs in.
The new problem I am having is when retrieving all of my images from parse for the current user, the images are displayed all out of order. Actually, just about every time the images are retrieved they are in a slightly different order. I tried looking at other posts where people had this problem but they didn't seem to do the trick.
Here is my code to retrieve all image posts by a user (the current user):
func retrieveAllImagesForUserId(userId:String){
self.arrayOfUserPosts.removeAll()
let query = PFQuery(className: "ImagePost")
query.whereKey("UserId", equalTo: userId)
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {
(object:[PFObject]?, error:NSError?) -> Void in
if ( error != nil ){
print(error?.localizedDescription, error?.userInfo)
} else {
for temp: PFObject in object! {
let username: String = temp["Username"] as! String
let userId: String = temp["UserId"] as! String
let description: String = temp["ImageDescription"] as! String
let imageId: String = temp.objectId!
let file: PFFile = temp["Image"] as! PFFile
file.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
let retrievedImage = UIImage(data: imageData)
self.imagePost = ImagePost.init(
image: retrievedImage!,
userId: userId,
imageId: imageId,
description: description,
username: username)
self.arrayOfUserPosts.append(self.imagePost!)
NSNotificationCenter.defaultCenter().postNotificationName("retrievedPost", object: nil)
}
}
}
}
}
}
}
The first thing i did was remove all objects to avoid any possible duplications to occur, maybe from a previous user who was logged on to the same device or anything like that.
For every image posted, i am also posting a column which has the users objectId whom posted that image. This way, i can query where said key is equal to the current users objectId.
I am doing an additional query to orderByDescending("createdAt") so the new images will be displayed at the top of my collection view.
My ImagePost class is an extremely simple class that is used for populating the area with objects, it looks like this:
class ImagePost {
var postedImage: UIImage?
var userId: String?
var imageId: String?
var description: String?
var username: String?
init(image:UIImage, userId:String, imageId:String, description: String, username: String ) {
self.postedImage = image
self.userId = userId
self.imageId = imageId
self.description = description
self.username = username
}
}
When the data is retrieved, i append the new ImagePost object to my array, which is the array i used to populate my collectionView and send a notification to reload the collection view.
I just really don't understand why I am having this problem so all of a sudden where the images are being retrieved in almost any order they choose. Any help would be greatly appreciated.
If you know the solution in objective-c but not swift that will also be helpful.
Thank you,
Rob
I had integrated something similar using Parse.
You don't need to fetch all the images at first. You can use a third party library SDWebImageCache for downloading the image when needed or caching.
Have the postedImage type as PFFile and assign the imageFile directly. No need of fetching the imageData.
Have another key called updatedAt in ImagePost class. No need of using predicate when querying the objects from Parse. Save the updatedAt time of ImagePost class. So now you can directly append the data to arrayOfUserPosts.
After completion of the loop, you can sort the array and assign it to self.arrayOfUserPosts.
Then in tableView's dataSource tableView:cellForRowAtIndexPath: method, you can do something like,
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:file.url] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
// Any custom view initialisation if needed.
}
where imageView is your display view for image, file is the object of type PFFile which represent the image. This is a Objective-C code. Similar syntax for Swift.

Can't retrieve a picture to swift from parse.com using their documentation

I have been trying to follow parse.com's intruction to retrieve a picture I already successfully uploaded (also using their documentation). My code:
let testObject = PFObject(className: "TestObject")
let file = testObject["SampleImage.png"] as PFFile
file.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
let image = UIImage(data:imageData)
self.mainImg.image = image
print("Image Retreived")
I am getting the error:
"AnyObject! is not convertible to 'PFFile'"
and then it sugests that I include a ! in 'as'. However, when I do, the application runs but does not retrieve anything.
I realize this question is posted elsewhere, but the answer is not working for me. What am I doing wrong?
let testObject = PFObject(className: "TestObject")
This is a new empty object which isn't backed by anything on the server. You need to set the id to a known value and refresh the instance of you need to run a query to find an object before the resulting object will contain anything.

Resources