I am attempting to fetch data from parse.com into my custom cell which is full of strings and images. I believe I am either retrieving my PFFile incorrectly from parse.com or I am retrieving the PFFile correctly but converting the file to UIImage improperly. The error i am receiving is going on within the loadData() function. It reads as follows: could not find an overload for 'init' that accepts the supplied arguments
Information
//Used to set custom cell
class Information {
var partyName = ""
var promoterName = ""
var partyCost = ""
var flyerImage: UIImage
var promoterImage: UIImage
init(partyName: String, promoterName: String, partyCost: String, flyerImage: UIImage, promoterImage: UIImage) {
self.partyName = partyName
self.promoterName = promoterName
self.partyCost = partyCost
self.flyerImage = flyerImage
self.promoterImage = promoterImage
}
}
Parse fetch function
func loadData() {
var findDataParse:PFQuery = PFQuery(className: "flyerDataFetch")
findDataParse.findObjectsInBackgroundWithBlock{
(objects: [AnyObject]?, error: NSError?) -> Void in
if (error == nil) {
for object in objects! {
var eventImage0 : UIImage
var eventImage10 : UIImage
let userImageFile = object["partyFlyerImage"] as! PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
let eventImage = UIImage(data:imageData!)
eventImage0 = eventImage!
}
}
let userImageFile1 = object["partyPromoterImage"] as! PFFile
userImageFile1.getDataInBackgroundWithBlock {
(imageData1: NSData?, error1: NSError?) -> Void in
if error1 == nil {
let eventImage1 = UIImage(data:imageData1!)
eventImage10 = eventImage1!
}
}
//Error below
var party1 = Information(partyName: (object["partyName"] as? String)!, promoterName: (object["partyPromoterName"] as? String)!,partyCost: (object["partyCost"] as? String)!, flyerImage: UIImage(data: eventImage0)!, promoterImage: UIImage(data: eventImage10)!)
self.arrayOfParties.append(party1)
}
}
self.tableView.reloadData()
}
}
You are fetching data from Parse in background, but processing on main thread. Try this:
func loadData() {
var findDataParse:PFQuery = PFQuery(className: "flyerDataFetch")
findDataParse.findObjectsInBackgroundWithBlock{
(objects: [AnyObject]?, error: NSError?) -> Void in
if (error == nil) {
for object in objects! {
var eventImage0 : UIImage
var eventImage10 : UIImage
let userImageFile = object["partyFlyerImage"] as! PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
let eventImage = UIImage(data:imageData!)
eventImage0 = eventImage!
let userImageFile1 = object["partyPromoterImage"] as! PFFile
userImageFile1.getDataInBackgroundWithBlock {
(imageData1: NSData?, error1: NSError?) -> Void in
if error1 == nil {
let eventImage1 = UIImage(data:imageData1!)
eventImage10 = eventImage1!
var party1 = Information(partyName: (object["partyName"] as? String)!, promoterName: (object["partyPromoterName"] as? String)!, partyCost: (object["partyCost"] as? String)!, flyerImage: UIImage(data: eventImage0)!, promoterImage: UIImage(data: eventImage10)!)
self.arrayOfParties.append(party1)
}
}
}
}
}
}
self.tableView.reloadData()
}
}
Your fetching your images Asynchronously and creating your Information cell Synchronously. So when you create the cell, the images are likely not loaded and your are in effect sending nil to the constructor for the cell.
In the following code you are retrieving the image data async:
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
let eventImage = UIImage(data:imageData!)
eventImage0 = eventImage!
}
}
So when you assign the image data to eventImage0, the call to the Information cell initializer has probably already happened.
You need to modify the code to instead of passing the image into the cell view initializer, allow you to access the UIImageview from the Information cell, so that when the background image loads complete you can simply set the loaded image into that UI/PF/ImageView.
Related
How do i convert an PFFile to an UIImage with swift?
In this code, the app is getting the file from parse and now i want it to show on a UIImageView, But i get an error...
Here is my code...
var ImageArray:UIImage = [UIImage]()
var textArray:String = [String]()
var query = PFQuery(className:"ClassName")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
//this works fine
self.textArray.append(object.valueForKey("Image")! as! String)
//this does not work...
self.ImageArray.append(object.valueForKey("Image")! as! PFFile)
//I get an error that says PFFile is not convertible to UIImage. How do i convert it?
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
PFFile is a parse representation of anykind of file. To get the "real" file (image), you need to call getDataInBackgroundWithBlock. Try it:
if let userPicture = object.valueForKey("Image")! as! PFFile {
userPicture.getDataInBackgroundWithBlock({
(imageData: NSData!, error NSError!) -> Void in
if (error == nil) {
let image = UIImage(data:imageData)
self.ImageArray.append(image)
}
})
}
Swift 1.2+ Version
if let userPicture = PFUser.currentUser()!.valueForKey("Image") as? PFFile {
userPicture.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
let image = UIImage(data:imageData!)
self.ImageArray.append(image)
}else{
print("Error: \(error)")
}
}
}
With Swift 3 on Parse.
if let photo = obj.file as? PFFile {
photo.getDataInBackground(block: {
PFDataResultBlock in
if PFDataResultBlock.1 == nil {//PFDataResultBlock.1 is Error
if let image = UIImage(data:PFDataResultBlock.0!){
//PFDataResultBlock.0 is Data
photoCell.attachedPicture.image = image
}
}
})
}
I have 4 functions containing Parse query.findObjectsInBackgroundWithBlock. These are being called to grab data and then populate the table view. Using dispatch groups.
Here is two examples of my parse querys
func getEventImages() {
print("getEventImages enter")
dispatch_group_enter(self.group)
let query = PFQuery(className: "events")
query.orderByAscending("eventDate")
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!, error: NSError!) -> Void in
// Initialize your array to contain all nil objects as
// placeholders for your images
if error == nil {
self.eventMainImageArray = [UIImage?](count: objects.count, repeatedValue: nil)
for i in 0...objects.count - 1 {
let object: AnyObject = objects[i]
let mainImage = object["mainImage"] as! PFFile
//dispatch_group_enter(self.group)
mainImage.getDataInBackgroundWithBlock({
(imageData: NSData!, error: NSError!) -> Void in
if (error == nil) {
let mainImage = UIImage(data:imageData)
self.eventMainImageArray[i] = mainImage
print("getEventImages appended")
}
else {
print("error!!")
}
})
}
}
print("getEventImages leave")
dispatch_group_leave(self.group)
}
}
func getEventInfo() {
print("eventInfo enter")
dispatch_group_enter(group)
let query = PFQuery(className: "events")
query.orderByAscending("eventDate")
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!,error: NSError!) -> Void in
self.eventNameArray = [String?](count: objects.count, repeatedValue: nil)
self.eventInfoArray = [String?](count: objects.count, repeatedValue: nil)
self.eventDateArray = [NSDate?](count: objects.count, repeatedValue: nil)
self.eventTicketsArray = [String?](count: objects.count, repeatedValue: nil)
if error == nil {
for i in 0...objects.count - 1 {
let object: AnyObject = objects[i]
let eventName = object["eventName"] as! String
let eventInfo = object["eventInfo"] as! String
let eventDate = object["eventDate"] as! NSDate
let eventTicket = object["Tickets"] as! String
self.eventNameArray[i] = eventName
self.eventInfoArray[i] = eventInfo
self.eventDateArray[i] = eventDate
self.eventTicketsArray[i] = eventTicket
print("event info appended")
}
}
print("event info leave")
dispatch_group_leave(self.group)
}
}
And my dispatch_group_nofity
dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
print("Finished reloadDataFromServer()")
self.tableView.reloadData()
self.refreshControl?.finishingLoading()
}
}
The problem is that its hit and miss if the data gets retrieved quick enough before dispatch_group_leave(self.group) is called leading to reloading the tableview data too soon. I need to get this so the dispatch_group_leave gets called when the appending is completed.
There is no need for two methods to retrieve the data, no need to unpack the data into multiple arrays and no need to use dispatch groups.
All you need is a simple method to retrieve your event data
var events:[PFObject]=[PFObject]()
func getEventInfo() {
let query = PFQuery(className: "events")
query.orderByAscending("eventDate")
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!,error: NSError!) -> Void in
if error==nil {
self.events=objects as! [PFObject]
self.tableView.reloadData()
} else {
print("Something went wrong! - \(error)"
}
self.refreshControl?.finishingLoading()
}
}
Then, you haven't shown your cellForRowAtIndexPath but you would have something like
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! MyTableViewCell
let event=self.events[indexPath.row]
cell.eventName.text=event["eventName"] as? String
cell.eventInfo.text=event["eventInfo"] as? String
if let mainImageFile=event["mainImage"] as? PFFile {
mainImageFile.getDataInBackgroundWithBlock({
(imageData: NSData!, error: NSError!) -> Void in
if (error == nil) {
let mainImage = UIImage(data:imageData)
cell.mainImage= mainImage
}
else {
print("error!!")
}
}
return cell;
}
You can use a PFImageView or a framework like SDWebImage to handle image caching and putting a placeholder image in place while the image is loaded.
If you want to update an event is as easy as
var event=self.events[someindex];
event["eventName"]=newValue
event.saveInBackground()
I am getting a fatal error: unexpectedly found nil while unwrapping an optional value. I get this error after the code gets to self.imageArray.append(image!) from this code:
func retrieveImages()
{
var query = PFQuery(className: "Maps")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil && objects != nil {
let objects = objects as! [PFObject]
for object in objects {
let imageFile = object["imageFile"] as! PFFile
imageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if imageData != nil {
let imageData:NSData! = imageData
let image = UIImage(data: imageData)
self.imageArray.append(image!)
}
}
}
}
}
}
}
I have checked each line of code and image does not become nil until i try to append it to the end of the imageArray.
like previous mentioned, you are reassigning a lot of variables. Try you if-let statements on the optional variables like this:
func retrieveImages(){
var query = PFQuery(className: "Maps")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) in
if let objects = objects as? [PFObject] where error == nil {
for object in objects {
if let imageFile = object["imageFile"] as? PFFile {
imageFile.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) in
if let imageData = imageData, let image = UIImage(data: imageData) {
self.imageArray.append(image)
}
}
}
}
}
}
}
I am trying to display an image from parse using swift. This is my code:
var query = PFQuery(className: "Maps")
query.getObjectInBackgroundWithId("1234asdf3456") {
(object: PFObject?, error: NSError?) -> Void in
if error == nil
{
println(object)
var objectAsPF = object as PFObject!
let file = objectAsPF["imageFile"] as! PFFile
file.getDataInBackgroundWithBlock {
(imageData:NSData?, error:NSError?) -> Void in
if error == nil {
if let imageData = imageData {
let map:UIImage = UIImage(data: imageData)!
self.MapView.image = map
println("success")
}
}
}
}
else
{
println(error)
}
}
I set a breakpoint at println("success") and i checked the variable values and everything is fine until i try to convert imageData to UIImage. Any tips?
Use this code to retrieve images from parse then convert it from a PFFile to a UIImage...
var query = PFQuery(className:"Maps")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
self.scored = objects!.count
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
let userImageFile = object["imageFile"] as! PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
let image = UIImage(data:imageData)
if image != nil {
self.imageArray.append(image!)
}
}
}
}
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
dispatch_async(dispatch_get_main_queue()) {
println("Finished Loading Image")
}
All,
I have a simple class in the parse backend - which feeds a uitableview. The data is stored in Arrays. I guess because all parse data is done in the background sometimes data gets downloaded before others. I have a very mixed up tableview. With images in the wrong cell etc. Also the custom cells are sometimes not showing up at all and I need to do a refresh.
Here is my code that I used to download all the data from parse and add into the arrays.
Can you have a look please and suggest a way to do this.
Also how can I add a placeholder image , before the original image comes up.
Also this code is in my ViewDidLoad, would it be better in an earlier function, hopefully so i don't have to relsoaddata on the tableview..
var query = PFQuery(className:"TableViewData")
query.includeKey("EventLoc")
query.findObjectsInBackgroundWithBlock{
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for object in objects {
let thumbNail = object["backgroundImage"] as PFFile
thumbNail.getDataInBackgroundWithBlock({
(imageData: NSData!, error: NSError!) -> Void in
if (error == nil) {
dispatch_async(dispatch_get_main_queue()) {
let image = UIImage(data:imageData)
self.CellBackgroundImage.append(image!)
}
}
})
var VenueLocation = object["EventLoc"] as PFObject!
VenueLocation.fetchIfNeededInBackgroundWithBlock {
(VenueLocation: PFObject!, error: NSError!) -> Void in
dispatch_async(dispatch_get_main_queue()) {
let VenueLocationTitle = VenueLocation["EventLocation"] as NSString
self.EventLocationArray.append(VenueLocationTitle)
}
}
let eventiconimage = object["EventIcon"] as PFFile
eventiconimage.getDataInBackgroundWithBlock({
(imageData: NSData!, error: NSError!) -> Void in
if (error == nil) {
dispatch_async(dispatch_get_main_queue()) {
let image = UIImage(data:imageData)
self.EventIconImageArray.append(image!)
}
}
})
dispatch_async(dispatch_get_main_queue()) {
self.TitleArray.append(object["EventTitle"] as String)
self.EventPriceArray.append(object["EventPrice"] as String)
self.EventStartDate.append(object["EventStartDate"] as NSDate)
self.EventEndDate.append(object["EventEndDate"] as NSDate)
self.tableView.reloadData()
}
You need to use serial queue then your array data will be in order. Whats happening because of concurrent task the data is not appended in order
var backgroundQueue:dispatch_queue_t = dispatch_queue_create("SerialQueue", DISPATCH_QUEUE_SERIAL)
var query = PFQuery(className:"TableViewData")
query.includeKey("EventLoc")
query.findObjectsInBackgroundWithBlock{
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for object in objects {
dispatch_async(backgroundQueue, { () -> () in
let thumbNail = object["backgroundImage"] as PFFile
thumbNail.getDataInBackgroundWithBlock({
(imageData: NSData!, error: NSError!) -> Void in
if (error == nil) {
dispatch_async(dispatch_get_main_queue()) {
let image = UIImage(data:imageData)
self.CellBackgroundImage.append(image!)
}
}
})
var VenueLocation = object["EventLoc"] as PFObject!
VenueLocation.fetchIfNeededInBackgroundWithBlock {
(VenueLocation: PFObject!, error: NSError!) -> Void in
dispatch_async(dispatch_get_main_queue()) {
let VenueLocationTitle = VenueLocation["EventLocation"] as NSString
self.EventLocationArray.append(VenueLocationTitle)
}
}
let eventiconimage = object["EventIcon"] as PFFile
eventiconimage.getDataInBackgroundWithBlock({
(imageData: NSData!, error: NSError!) -> Void in
if (error == nil) {
dispatch_async(dispatch_get_main_queue()) {
let image = UIImage(data:imageData)
self.EventIconImageArray.append(image!)
}
}
})
dispatch_async(dispatch_get_main_queue()) {
self.TitleArray.append(object["EventTitle"] as String)
self.EventPriceArray.append(object["EventPrice"] as String)
self.EventStartDate.append(object["EventStartDate"] as NSDate)
self.EventEndDate.append(object["EventEndDate"] as NSDate)
self.tableView.reloadData()
}
});
}
}