How to fix "getDataInBackgroundWithBlock" error in swift - swift

Can't I use "getDataInBackgroundWithBlock" for PFQuery?
I tried to get picture from the server.
But the code doesn't work at all.
Xcode usually provides autocomplete code function.
But "getDataInBackgroundWithBlock" wasn't worked.
How can I fix this?
Please check the below code.
let information = PFQuery(className: "messages")
information.findObjectsInBackground { (objects, error) in
if error == nil {
for object in objects!{
self.messageLbl.text = object["message"] as? String
self.receiverLbl.text = object["receiver"] as? String
self.senderLbl.text = object["sender"] as? String
object["picture"].getDataInBackgroundWithBlock({ (data, error) in
if error == nil {
if data != nil{
self.picture.image = UIImage(data : data!)
}else{
print(error)
}
}
})
}
}else{
print(error)
}
}
the error message is "Value of type 'Any?' has no member 'getDataInBackgroundWithBlock'"

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

Value of type 'error' has no member 'userinfo'

My code is as follows:
if signupMode {
let user = PFUser()
user.username = emailTextField.text
user.email = emailTextField.text
user.password = passwordTextField.text
user.signUpInBackground(block: {
(success, error) in
if error != nil {
let displayErrorMessage = "Please try again later"
if let errorMessage = error.UserInfo["error"]? as String {
displayErrorMessage = errorMessage
}
self.createAlert(title: "Error", message: "Parse Error")
}
I just keep getting the error
"value of type 'error' has no member 'userinfo"
What can I do to fix this? I'm using Xcode 8
By your snipped it can't be determined what error is and wether it should have a member called UserInfo. Please provide more code...
I assume it is an NSError? In this case it would be error.userInfo as member name. (watch the casing)
Other than that your code will fail compiling because you declare let displayErrorMessage but in the if make an assignment to it. You would need to change it to var displayErrorMessage to be able to do that.
Try this:
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
if error == nil {
// Perform a segue, show a message or whatever you want
} else {
let errorString = error.userInfo["error"] as NSString
// Show the errorString somewhere and let the user try again.
}
}
If you're still getting this error, try this code. Force unwrap error as NSError.
if let errorMessage = (error! as NSError).userInfo["error"] as? String {
displayErrorMessage = errorMessage
}

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

fatal error: unexpectedly found nil while unwrapping an Optional value. Swift

I am new in Swift. My question is I am not sure how to unwrapping the optional value. When I print the object.objectForKey("profile_picture"), I can see Optional(<PFFile: 0x7fb3fd8344d0>).
let userQuery = PFUser.query()
//first_name is unique in Parse. So, I expect there is only 1 object I can find.
userQuery?.whereKey("first_name", equalTo: currentUser)
userQuery?.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in
if error != nil {
}
for object in objects! {
if object.objectForKey("profile_picture") != nil {
print(object.objectForKey("profile_picture"))
self.userProfilePicture.image = UIImage(data: object.objectForKey("profile_pricture")! as! NSData)
}
}
})
You'd use if let to perform "optional binding", only performing the block if the result in question is not nil (and binding the variable profilePicture to the unwrapped value in the process).
It would be something like:
userQuery?.findObjectsInBackgroundWithBlock { objects, error in
guard error == nil && objects != nil else {
print(error)
return
}
for object in objects! {
if let profilePicture = object.objectForKey("profile_picture") as? PFFile {
print(profilePicture)
do {
let data = try profilePicture.getData()
self.userProfilePicture.image = UIImage(data: data)
} catch let imageDataError {
print(imageDataError)
}
}
}
}
Or, if you want to get data asynchronously, perhaps:
userQuery?.findObjectsInBackgroundWithBlock { objects, error in
guard error == nil && objects != nil else {
print(error)
return
}
for object in objects! {
if let profilePicture = object.objectForKey("profile_picture") as? PFFile {
profilePicture.getDataInBackgroundWithBlock { data, error in
guard data != nil && error == nil else {
print(error)
return
}
self.userProfilePicture.image = UIImage(data: data!)
}
}
}
}
It would be something along those lines, using if let to unwrap that optional. And you then have to get the NSData associated with that the PFFile object (from the getData method or getDataInBackgroundWithBlock, presumably).
See Optional Binding discussion in The Swift Programming Language.

Fetch request in Swift 2.1.1

I'm trying to convert my Swift 1 code into Swift 2.1.1 code.
So I am trying to add a fetchRequest.
In Swift 1 I did this:
if let results = context.executeFetchRequest(fetchRequest, error:&error),
let managedObject = results.first as? NSManagedObject {
context.deleteObject(managedObject)
}
let saveError: NSError?
context.save(nil)
and
var error: NSError?
let fetchedResults = managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]?
if let results = fetchedResults {
people = results
}
else {
print("Could not fetch \(error), \(error!.userInfo)")
}
Swift 2.1 (2nd request -> doesn't work):
do {
let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
// success if it gets here
if let results = fetchedResults {
people = results
}
} catch let error as NSError {
// failed so print error
print("Error: \(error.localizedDescription)")
}
Errors in line (if let results... & let fetchedResults...):
Initializer for conditional binding must have Optional type, not '[AnyObject]'
Call can throw, but is not marked with 'try' and the error is not handled
Errors in line (let fetchedResults...):
Call can throw, but is not marked with 'try' and the error is not handled
Cannot downcast from '[AnyObject]' to a more optional type '[NSManagedObject]?'
Could you please help me to translate this into Swift 2.1.1?
Thanks for your help!
You can wrap it in a do catch block. It will print an error if the let results line fails.
do {
let results = try context.executeFetchRequest(fetchRequest)
// success if it gets here
if let managedObject = results.first as? NSManagedObject {
context.deleteObject(managedObject)
}
} catch let error as NSError {
// failed so print error
print("Error: \(error.localizedDescription)")
}
EDIT
Second request:
do {
let fetchedResults = try managedContext.executeFetchRequest(fetchRequest)
// success if it gets here
if let results = fetchedResults as? [NSManagedObject]{
people = results
}
} catch let error as NSError {
// failed so print error
print("Error: \(error.localizedDescription)")
}