Parse/Image not loads the image from the server? - swift

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

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.

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

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

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