Load image from parse.com - swift

How do I load images and image text saved in parse.com?
This is my function for uploading the image:
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 add image and text in tableview, and make it a scroll look-a-like like instagram if there are more then 1 image?

Here is the code to load an image from parse
PFFile *profile = user[#"profilePic"];
if (profile)
{
[profile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
if (!error)
{
UIImage *profilePic = [UIImage imageWithData:imageData];
//Here is your image use it
}
else
{
//error
}
}];
}

First part of question is duplicate as remus pointed out:
Retrieving image from parse.com You will need to query for the image data and convert to a uiimage.
Second part of question:
Just store the queried images and text in array, then make custom uitableviewcells that hold a uiimageview and textview. Populate the tableviewcells with data from array.

Related

Retrieve firebase Image - ImageView

Hello everyone I am trying to take my image from the firebase database and present it into an image view as the profile image of the user. The first thing I do is create a method to retrieve the photo data in an array
class PhotoService {
static func retrievePhotos(completion: #escaping ([Photo]) -> Void) {
//get a databas refrence
let db = Firestore.firestore()
//get data from "photos" collection
db.collection("photos").getDocuments { (snapshot, Error) in
//check for errors
if Error != nil {
//error in retrieving photos
return
}
//get all the documents
let documents = snapshot?.documents
//check that documents arent nil
if let documents = documents {
//create an array to hold all of our photo structs
var photoArray = [Photo]()
//loop through documents, get a photos struct for each
for doc in documents {
//create photo struct
let p = Photo(snapshot: doc)
if p != nil {
//store it in an array
photoArray.insert(p!, at: 0)
}
}
//pass back the photo array
completion(photoArray)
}
}
}
Then I call that class and attempt to display the Image in the image view
#IBOutlet var profilePictureImageView: UIImageView!
var photos = [Photo]()
override func viewDidLoad() {
super.viewDidLoad()
//call the photo service to retrieve the photos
PhotoService.retrievePhotos { (retrievedPhotos) in
//set the photo array to the retrieved photos
self.photos = retrievedPhotos
//make the image view a circle
self.profilePictureImageView.layer.cornerRadius = self.profilePictureImageView.bounds.height / 2
self.profilePictureImageView.clipsToBounds = true
//make the image view display the photo
var photo:Photo?
func displayPhoto(photo:Photo) {
//check for errors
if photo.photourl == nil {
return
}
//download the image
let photourl = URL(string: photo.photourl!)
//check for erorrs
if photourl == nil {
return
}
//use url session to download the image asynchronously
let session = URLSession.shared
let dataTask = session.dataTask(with: photourl!) { (data, response, Error) in
//check for errors
if Error == nil && data != nil {
//let profilePictureImageView = UIImage()
let image = UIImage(data: data!)
//set the image view
DispatchQueue.main.async {
self.profilePictureImageView.image = image
}
}
}
dataTask.resume()
}
}
}
}
I dont understand what I am doing wrong and why the image is not showing up if anyone can explain this to me and give me an example with code that would be amazing, explain it as though you are explaining it to a kid in grade 5
A quick way to get Image from Firebase and assigning it to an ImageView can be done easily in these Steps.
Function to Get PhotoUrl
//Function to get photo of loggedin User
func getUrl(Completion:#escaping((String)->())) {
let userID = Auth.auth().currentuser?.uid
let db = Firestore.firestore().collection("photos").document(userID)
db.getDocument { (docSnapshot, error) in
if error != nil {
return
} else {
guard let snapshot = docSnapshot, snapshot.exists else {return}
guard let data = snapshot.data() else {return}
let imageUrl = data["photoUrl"] as! String
completion(imageUrl)
}
}
}
To download image and assign it to image view
//Call this function in VC where your `ImageView` is
func getImage(Url:String){
DispatchQueue.global().async {
let url = URL(string: Url)
if let data = try? Data(contentsOf: url!) {
DispatchQueue.main.async {
self.profilePictureImageView.image = UIImage(data: data)
}
}
}
}
}
Call these inside viewDidLoad like this:
getUrl{(url) in
getImage(Url:url)
}

Swift 3: cant get image from Parse?

Ok, I have looked at questions like How do you access an object's fields from a Parse query result in Swift? but the answer is not working in Swift 3. With the following trying to get an image from the first PFObject in Parse I get the error:
Cannot convert value type NSData, NSError -> Void to expected
PFDataResultBlock ?
var query = PFQuery(className: PARSE_CLASS!)
query.order(byDescending: "createdAt")
query.findObjectsInBackground {
(objects, error) -> Void in
if error == nil {
//print(objects?.first?["testTxt"] as! NSString)
//print(objects?.first?["testImg"] as! PFFile)
let thumbnail = objects?.first?["testImg"] as! PFFile
thumbnail.getDataInBackgroundWithBlock{(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let image = UIImage(data: imageData!) {
//get image here
}
}
}
}
I have tried changing the type and everything. How can I store an image from Parse in recent Swift?
You can try this:
if let validObjects = objects {
for object in validObjects {
let thumbnail = object["testImg"] as? PFFile
thumbnail?.getDataInBackground (block: { (data, error) -> Void in
//read image here
}
}
}

Load user image

I use this code to load users usernames when a user search for another user
var user: PFUser? {
didSet {
userNameLabel.text = user?.username
}
}
How can I do the same thing but for profile pictures?
Here is what you can do.
case 1
If you need to download the image and display then -
Create a property that holds url for the image.
Asynchronously download image and display
So code would look this this
var pictureURL: NSURL?
var user: PFUser? {
didSet {
userNameLabel.text = user?.username
pictureURL = user?.pictureURL
displayPicture()
}
}
private func displayPicture() {
// Async download pic and display
}
case 2
If you have the image locally then just display -
var user: PFUser? {
didSet {
userNameLabel.text = user?.username
userImage.image = UIImage(named: "Picturename")
}
}
You can not save your image file with UIImage format on Parse.com. You can store the file with PFFile and you have to convert your image to PFFile for saving and getting the image.
You can save your Image with this function;
private func saveLogo() {
let yourLogoImageFile = UIImage(named: "YourLogoFileName")
if let imageData = UIImageJPEGRepresentation(yourLogoImageFile!, 0.1) {
// You got the PFFile you can use this for save.
let imagePFFile = PFFile(name: "logo.png", data: imageData)
logo = imagePFFile // Send this PFFile to your variable or just save.
// Saving...
imagePFFile?.saveInBackground()
}
}
After that you can get your logo PFFile from Parse and you have to convert it to UIImage with this function;
private func getLogo() {
if let image = yourLogoVariable {
image.getDataInBackgroundWithBlock() {
(let imageData, error) in
if error == nil {
if let logoImageData = imageData {
if let logoImage = UIImage(data: logoImageData) {
// logoImage is the UIImage you can use this for your UIImageView.
}
}
}
}
}
}

I want to save UIImage instead of nil value on parse

I am implementing saving post part, the post contains user profile Picture when it is saved for showing on main page. but there would be a user who hasn't profile picture. I tried this code, it occurs error.
if let profilePicture = PFUser.currentUser()?.objectForKey("profile_picture") {
post["profile_picture"] = profilePicture
} else {
post["profile_picture"] = UIImage(named: "AvatarPlaceholder" )
}
post.saveInBackgroundWithBlock({ ( isSucessful: Bool, error : NSError?) -> Void in
if error == nil {
self.alert("success", message : "your post has been uploaded")
} else {
self.alert("Error", message : (error?.localizedDescription)!)
}
if user has profile photo, it will be fine. but if not, that is the problem.
I have Avatarplaceholder jpeg file in assets.
my questions are.....
how can I upload my avatarplaceHolder ?
or is there better way to cover nil value?,
actually I don't want to waste my cloud storage.
I guess that you have to wrap you UIImage into a PFFile as follows:
let imageData = UIImageJPEGRepresentation(UIImage(named: "AvatarPlaceholder")!, 0.5)!
let profileImageFile = PFFile(name: "profileImage", data: imageData)
post["profile_picture"] = profileImageFile

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.