List view populated with firebase query results problem SWIFT IOS - ios

Hello I'm trying to do a List that is populated with query results from Firebase Database
I've got constantly some problems and i have no clue what can i try to do next ive looked through internet to help me do this but found nothing, can you help me?
Thanks in Advance
Here is the code with errors
class BoatListViewContoller: UIViewController, UITableViewDelegate, UITableViewDataSource {
var title = [""] // Here error is saying "Property 'title' with type '[String]' cannot override a property with type 'String?'"
var lenght:Int?
func readProducts(){
let db = Firestore.firestore()
db.collection("products").getDocuments(){
querySnapshot, err in
if let err = err {
print("Error getting documents: \(err)")
} else {
self.lenght = querySnapshot!.count
for document in querySnapshot!.documents{
self.title.append(document.data()["title"] as! String) // Here i got a error saying "No exact matches in call to subscript"
}
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lenght!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath)
cell.textLabel!.text = title[indexPath]
cell.backgroundColor = UIColor.init(red: 212/255, green: 255/255, blue: 241/255, alpha: 1)
return cell
}
private var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad();
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height
myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: displayWidth, height: displayHeight))
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
myTableView.dataSource = self
myTableView.delegate = self
myTableView.backgroundColor = UIColor.init(red: 212/255, green: 255/255, blue: 241/255, alpha: 1)
view.addSubview(myTableView)
}
}

First error:
UIViewController already has a property named title:
open var title: String?
You just need to rename var title = [""] to var titles = ["], or something different than title.
Second error:
You might try document.get("title") as! String (borrowed the idea from https://stackoverflow.com/a/54601354/3227743), or you might try
let data = document.data()
let title = data["title"]
or
self.title.append((document.data())["title"] as! String)
Miscellaneous:
You would also need to call myTableView.reloadData() after parsing every document.
Nitpick: length instead of lenght. Also, you actually don't need that since you could (should) just use titles.count instead.

Related

blocking phone number in call kit

I'm trying to using CallKit to add a feature to my app to add some phone numbers to blacklist!
the code below is my whole view!!
class BlacklistViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate {
var phoneNumbersArrCoreData = [BlockedPhoneNumbers]()
var listPhoneNumbers:[CXCallDirectoryPhoneNumber] = []
#IBOutlet weak var TableView: UITableView!
#IBOutlet weak var BtnAddO: UIButton!
#IBOutlet weak var EntPhonenumber: UITextField!
#IBAction func BtnAddA(_ sender: Any) {
if !(EntPhonenumber.text?.isEmpty)!
{
let blackedPhonenumbers_CoreData = BlockedPhoneNumbers(context: PersistanceService.context)
blackedPhonenumbers_CoreData.phoneNumber = Int64.init(EntPhonenumber.text!)!
PersistanceService.saveContext()
getCoreData()
TableView.reloadData()
}
}
var coreData = [BlockedPhoneNumbers]()
func getCoreData()
{
listPhoneNumbers.removeAll()
let fetchRequest : NSFetchRequest<BlockedPhoneNumbers> = BlockedPhoneNumbers.fetchRequest()
do
{
let FetchedResultFromDB = try PersistanceService.context.fetch(fetchRequest)
coreData = FetchedResultFromDB
print("============\n===========\n")
if coreData.count > 0
{
for i in 0..<coreData.count
{
listPhoneNumbers.append(coreData[i].phoneNumber)
}
}
print("============\n===========\n")
}
catch{
print("gettin blocked number from db got error")
}
}
override func viewDidLoad() {
BtnAddO.layer.cornerRadius = 5
BtnAddO.layer.borderColor = UIColor.white.cgColor
BtnAddO.layer.borderWidth = 0.8
EntPhonenumber.attributedPlaceholder = NSAttributedString(string: "Enter a phone number to block",attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightText])
getCoreData()
super.viewDidLoad()
view.backgroundColor = UIColor.init(red: 25/255, green: 28/255, blue: 46/255, alpha: 1)
TableView.delegate = self
TableView.dataSource = self
}
func beginRequest(with context: CXCallDirectoryExtensionContext) {
getCoreData()
let blockedPhoneNumbers: [CXCallDirectoryPhoneNumber] = listPhoneNumbers
for phoneNumber in blockedPhoneNumbers.sorted(by: <) {
context.addBlockingEntry(withNextSequentialPhoneNumber: phoneNumber)
}
context.completeRequest()
}
//MARK: - TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listPhoneNumbers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BlackListCell") as? BlackListTableViewCell
cell?.ContactImg.layer.masksToBounds = true
cell?.mainView.layer.cornerRadius = 10
cell?.mainView.backgroundColor = UIColor(red: 42/255, green: 48/255, blue: 66/255, alpha: 1)
cell?.ContactImg.layer.cornerRadius = 5
cell?.ContactImg.image = UIImage(named: "Blocked")
cell?.unBlock.imageView?.image = nil
cell?.unBlock.setTitle("UNBLOCK", for: UIControl.State.normal)
cell?.unBlock.layer.cornerRadius = (cell?.unBlock.frame.size.height)!/2
cell?.SetUnblockBtn {
I get the error here,below
let context:NSManagedObjectContext = PersistanceService.context
context.delete(self.phoneNumbersArrCoreData[indexPath.row] as NSManagedObject)
self.phoneNumbersArrCoreData.remove(at: indexPath.row)
print("data deleted!!!")
}
cell?.phoneNumber.text = String(listPhoneNumbers[indexPath.row])
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 85
}
}
to explain the code, I save each number that user will enter in a core data(entityName: BlockedPhoneNumbers). I'm not sure even if this is the right way to save numbers that they need to be blocked or not!!
when the user presses the button I save the number and it works fine( but I'm not sure if this is the right way or not!!).
and in getCoreData I get the core data and show them in a table view. which shows that core data works fine! but when user wanna unblock the contact and presses the button in CELL of the table view, I get an error and app crash and it says:
Thread 1: Fatal error: Index out of range
my problems are:
why do I get this error?
2.as I can not find any tutorial for callKit I believe that I'm doing this job wrong.
could anyone help me with this?
You have too many arrays:
listPhoneNumbers which contains your integer numbers
coreData which contains your Core Data items
phoneNumbersArrCoreData which could contain your Core Data items, but you don't add anything to it.
As a result, phoneNumbersArrCoreData is empty. When you try and remove an object from the empty array you get an array bounds exception.
You should eliminate two of the three arrays.
class BlacklistViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate {
var blockedNumbers = [BlockedPhoneNumbers]()
#IBOutlet weak var TableView: UITableView!
#IBOutlet weak var BtnAddO: UIButton!
#IBOutlet weak var EntPhonenumber: UITextField!
#IBAction func BtnAddA(_ sender: Any) {
if !(EntPhonenumber.text?.isEmpty)!
{
let blackedPhonenumbers_CoreData = BlockedPhoneNumbers(context: PersistanceService.context)
blackedPhonenumbers_CoreData.phoneNumber = Int64.init(EntPhonenumber.text!)!
PersistanceService.saveContext()
getCoreData()
TableView.reloadData()
}
}
func getCoreData()
{
let fetchRequest : NSFetchRequest<BlockedPhoneNumbers> = BlockedPhoneNumbers.fetchRequest()
do
{
let FetchedResultFromDB = try PersistanceService.context.fetch(fetchRequest)
blockedNumbers = FetchedResultFromDB
print("============\n===========\n")
}
catch{
print("gettin blocked number from db got error")
}
}
override func viewDidLoad() {
BtnAddO.layer.cornerRadius = 5
BtnAddO.layer.borderColor = UIColor.white.cgColor
BtnAddO.layer.borderWidth = 0.8
EntPhonenumber.attributedPlaceholder = NSAttributedString(string: "Enter a phone number to block",attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightText])
getCoreData()
super.viewDidLoad()
view.backgroundColor = UIColor.init(red: 25/255, green: 28/255, blue: 46/255, alpha: 1)
TableView.delegate = self
TableView.dataSource = self
}
//MARK: - TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return blockedNumbers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BlackListCell") as? BlackListTableViewCell
cell?.ContactImg.layer.masksToBounds = true
cell?.mainView.layer.cornerRadius = 10
cell?.mainView.backgroundColor = UIColor(red: 42/255, green: 48/255, blue: 66/255, alpha: 1)
cell?.ContactImg.layer.cornerRadius = 5
cell?.ContactImg.image = UIImage(named: "Blocked")
cell?.unBlock.imageView?.image = nil
cell?.unBlock.setTitle("UNBLOCK", for: UIControl.State.normal)
cell?.unBlock.layer.cornerRadius = (cell?.unBlock.frame.size.height)!/2
cell?.SetUnblockBtn {
let context:NSManagedObjectContext = PersistanceService.context
context.delete(self.blockedNumbers[indexPath.row] as NSManagedObject)
self.phoneNumbersArrCoreData.remove(at: indexPath.row)
print("data deleted!!!")
}
cell?.phoneNumber.text = blockedNumbers[indexPath.row].phoneNumber
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 85
}
}
The code to actually load data into the Call Kit block list needs to go into a CallKit extension in your app. You will need to use an application group to share the Core Data store with the extension.

Three entities hierarchical but in the third the first isn't accounted

I have an app with three TableViews and each is in a separate ViewController. I want pass the data from the firstVC to the secondVC to the thirdVC. Club -> Member -> transaction. If there is just one club, there is no problem.
In the second club, there are the members from the second club, which has to be like this.
Problem
But if the user clicks on the member, there are the transactions from the members of the first club at the indexPath from the first club.
My thoughts
So I have to account the club as well to the transactions. But my solutions just threw errors.
So maybe you have a good solution. I found a solution here but this didin't helped me.
Here is my TableView code:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return member?.transactions?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableViewTransaction.dequeueReusableCell(withIdentifier: "transactionCell", for: indexPath)
if let transaction = member?.transactions?[indexPath.row] {
cell.textLabel?.text = transaction.reason
let moneystring = String(transaction.money)
cell.detailTextLabel?.text = moneystring + " Fr."
if transaction.money < 0.0 {
cell.detailTextLabel?.textColor = UIColor.red
}
if transaction.money > 0.0 {
cell.detailTextLabel?.textColor = UIColor(red: 0, green: 110/255, blue: 0, alpha: 0.8)
}
}
return cell
}
Club fetch:
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate
else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchrequest: NSFetchRequest <Verein> = Verein.fetchRequest()
do {
clubs = try managedContext.fetch(fetchrequest)
tableViewClub.reloadData()
} catch {
print("Could not fetch")
Member fetch:
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchrequest: NSFetchRequest<Member> = Member.fetchRequest()
do {
members = try managedContext.fetch(fetchrequest)
self.tableViewMember.reloadData()
} catch {
print("Could not fetch")
}
Description of the App-
UITableView cells are reused, so if you load a previously used cell -- with its label's already set -- could be used for a new one. Because you're only setting the cell's labels if a transaction is found, if no transaction is found the cell will simply show the data that was previously loaded. You need to do something like this.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableViewTransaction.dequeueReusableCell(withIdentifier: "transactionCell", for: indexPath)
// clear the cell
cell.textLabel?.text = "" // blank or whatever the default should be
cell.detailTextLabel?.text = ""
// load any new data
if let transaction = member?.transactions?[indexPath.row] {
cell.textLabel?.text = transaction.reason
let moneystring = String(transaction.money)
cell.detailTextLabel?.text = moneystring + " Fr."
if transaction.money < 0.0 {
cell.detailTextLabel?.textColor = UIColor.red
}
if transaction.money > 0.0 {
cell.detailTextLabel?.textColor = UIColor(red: 0, green: 110/255, blue: 0, alpha: 0.8)
}
}
return cell
}

How to solve Fatal error: Index out of range in Swift IOS

I have a problem with a code is a RSS reader app for IOS. I have an error Thread 1: Fatal error: Index out of range.
I wrote on which line the error is.
By the way, this error does happen with all the RSS link I put for example with sky news RSS URL it works well but with some site (like the one I put now) it is not running and write Fatal error: Index out of range ERROR.
The Code:
import UIKit
class FeedListViewController: UITableViewController, XMLParserDelegate {
var myFeed : NSArray = []
var feedImgs: [AnyObject] = []
var url: URL!
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140
tableView.backgroundColor = UIColorFromRGB(rgbValue: 0x00B6ED)
self.tableView.dataSource = self
self.tableView.delegate = self
loadData()
}
#IBAction func refreshFeed(_ sender: Any) {
loadData()
}
func loadData() {
url = URL(string: "https://www.widgeti.co.il/feed")!
loadRss(url);
}
func loadRss(_ data: URL) {
// XmlParserManager instance/object/variable
let myParser : XmlParserManager = XmlParserManager().initWithURL(data) as! XmlParserManager
// Put feed in array
feedImgs = myParser.img as [AnyObject]
myFeed = myParser.feeds
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "openPage" {
let indexPath: IndexPath = self.tableView.indexPathForSelectedRow!
let selectedFURL: String = (myFeed[indexPath.row] as AnyObject).object(forKey: "link") as! String
// Instance of our feedpageviewcontrolelr
let fivc: FeedItemViewController = segue.destination as! FeedItemViewController
fivc.selectedFeedURL = selectedFURL as String
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myFeed.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.backgroundColor = UIColor.clear
cell.detailTextLabel?.backgroundColor = UIColor.clear
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor(white: 1, alpha: 0.1)
} else {
cell.backgroundColor = UIColor(white: 1, alpha: 0.2)
}
// Load feed iamge.
let url = NSURL(string:feedImgs[indexPath.row] as! String) //ERROR Thread 1: Fatal error: Index out of range
let data = NSData(contentsOf:url! as URL)
var image = UIImage(data:data! as Data)
image = resizeImage(image: image!, toTheSize: CGSize(width: 80, height: 80))
let cellImageLayer: CALayer? = cell.imageView?.layer
cellImageLayer!.cornerRadius = 35
cellImageLayer!.masksToBounds = true
cell.imageView?.image = image
cell.textLabel?.text = (myFeed.object(at: indexPath.row) as AnyObject).object(forKey: "title") as? String
cell.textLabel?.textColor = UIColor.white
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = .byWordWrapping
cell.detailTextLabel?.text = (myFeed.object(at: indexPath.row) as AnyObject).object(forKey: "pubDate") as? String
cell.detailTextLabel?.textColor = UIColor.white
return cell
}
func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
func resizeImage(image:UIImage, toTheSize size:CGSize)->UIImage{
let scale = CGFloat(max(size.width/image.size.width,
size.height/image.size.height))
let width:CGFloat = image.size.width * scale
let height:CGFloat = image.size.height * scale;
let rr:CGRect = CGRect(x: 0, y: 0, width: width, height: height)
UIGraphicsBeginImageContextWithOptions(size, false, 0);
image.draw(in: rr)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return newImage!
}
}
Can You help me solve this problem?
Thanks!
Fatal error: Index out of range
This error only refers a thing that index, you want to access from the array does not exist.
let url = NSURL(string: feedImgs[indexPath.row] as! String)
In the above line feedImgs[indexPath.row] does not exist, that why you are getting the error. Make sure that your feedImgs array and myFeed array both are of same length because you are loading the table from myFeed array.
Or, You can can check like this.
if feedImgs.count > indexPath.row {
let url = NSURL(string: (feedImgs[indexPath.row] ?? ""))
}
Fatal error: Index out of range
This error will happen if your index is out of range
If an array have 3 integer values 100, 150, 300 then it stores like that
array[0]=100
array[1]=150
array[2]=300
So the index range is [0 to array.count - 1], that means 0, 1, 2
If the index is negative or greater than or equal array count then this will occur. It means error will happen if indx < 0 || indx >= array.count

How can I filter more than one thing out of return from API in Swift 3

I am including my code that I have implemented to filter through sortedDiscipline names.
The problem I am having --even though it is filtering through the names-- is after the IndexPath.row is changed from the filtering, the image is incorrect for the current game, and also the cell that is populated cannot be selected because the didSelectRow does not follow the broken IndexPath.
import UIKit
import Foundation
import Alamofire
import SwiftyJSON
import Firebase
import FirebaseDatabase
class AllGamesTableViewController: UITableViewController, UISearchResultsUpdating {
let urlFront = "https://www.toornament.com/disciplines/"
let urlImagePath = "/img/icon-48x48-medium.png"
var selectedRow: Int?
var newArray = [String]()
var filteredGames = [String]()
var searchController: UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
searchController = UISearchController(searchResultsController:nil)
searchController.dimsBackgroundDuringPresentation = true
searchController.searchBar.sizeToFit()
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.searchBarStyle = UISearchBarStyle.minimal
// Include the search bar within the navigation bar.
navigationItem.titleView = self.searchController.searchBar
definesPresentationContext = true
tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = #colorLiteral(red: 0.1137254902, green: 0.168627451, blue: 0.1764705882, alpha: 1)
self.view.backgroundColor = #colorLiteral(red: 0.1137254902, green: 0.168627451, blue: 0.1764705882, alpha: 1)
self.navigationItem.setHidesBackButton(true, animated: true)
// self.navigationItem.setHidesBackButton(true, animated: true)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (searchController?.isActive)!{
return filteredGames.count
}else{
return ApiManager.shared.sortedDisipline.count
}
}
let getID = ApiManager.shared.disciplinesID
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "allGamesCell", for: indexPath)
cell.backgroundColor = UIColor(red: 29.0/255.0, green: 43.0/255.0, blue: 45.0/255.0, alpha: 1)
cell.textLabel?.textColor = #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1)
let disciplineid = ApiManager.shared.sortedDisciplineID[indexPath.row]
if (searchController?.isActive)!{
cell.textLabel?.text = filteredGames[indexPath.row]
cell.textLabel?.textColor = UIColor(red: 255.0/255.0, green: 165.0/255.0, blue: 0.0/255.0, alpha: 1)
cell.imageView?.image = UIImage(named: "\(disciplineid).png")
}else{
cell.textLabel?.textColor = UIColor(red: 255.0/255.0, green: 165.0/255.0, blue: 0.0/255.0, alpha: 1)
cell.textLabel?.text = ApiManager.shared.sortedDisipline[indexPath.row]
cell.imageView?.image = UIImage(named: "\(disciplineid).png")
}
return cell
}
func updateSearchResults(for searchController: UISearchController) {
filteredGames.removeAll(keepingCapacity: false)
//filter through the all games
filteredGames = ApiManager.shared.sortedDisipline.filter {
game in
game.lowercased().contains(searchController.searchBar.text!.lowercased())
}
// if searchController.searchBar.text != ""{
tableView.reloadData()
}
// }
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if searchController.isActive && searchController.searchBar.text != "" {
print(indexPath.row)
let DisciplineID = filteredGames[indexPath.row]
TournamentStore.shared.currentDisciplineId = DisciplineID
performSegue(withIdentifier: "tournamentList", sender: self)
} else {
let DisciplineID = ApiManager.shared.sortedDisciplineID[indexPath.row]
print("\(DisciplineID) \("did on click")")
TournamentStore.shared.currentDisciplineId = DisciplineID
performSegue(withIdentifier: "tournamentList", sender: self)
}
}
Suggestions to solve the issues.
Do not use separate arrays for disciplinesID and sortedDisipline
Use the class or struct representing discipline for both the data source array and the filteredGames array.
Get the disciplineid always directly from the discipline object. (Solves the image issue)
In didSelectRowAt get the object depending on searchController?.isActive like in the other methods (solves the indexPath issue)
PS: Initialize the search controller lazily and non-optional. That avoids a lot of question and exclamation marks.
Migrated from my comment for more explanation.
The reason your selection is incorrect is in your didSelectRowAt indexPath if you are searching you are not using the filtered list to get the ID. This is also why the image is wrong when reloading, you need to get the ID out of the filtered array if sorting
Something like this:
let id: String
if filtering {
id = filteredGames[indexPath.row]
} else {
id = ApiManager.shared.sortedDisciplineID[indexPath.row])
}
then use that id for the image and for opening it. Essentially when you sort you are changing how the names match up with the row ID's.
Most of my problem was that
searchController.dimsBackgroundDuringPresentation was set to true....it needed to be false.

Retrieving Image, String and Int from Parse

I have to retrieve images from Parse, and I am working on this code:
class ViewControllerHome: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var MessageTable: UITableView!
let color = UIColor(red: 0.0/255.0, green: 105.0/255.0, blue: 92.0/255.0, alpha: 1)
let colore = UIColor.whiteColor()
let coloree = UIColor(red: 33.0/255.0, green: 33.0/255.0, blue: 33.0/255.0, alpha: 1)
var Username = [String]()
var Image = [PFFile]()
var Likes = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
var refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: Selector("refreshPulled"), forControlEvents: UIControlEvents.ValueChanged)
loadData()
self.MessageTable.reloadData()
self.navigationController?.navigationBar.barTintColor = color
self.navigationController?.navigationBar.tintColor = colore
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: colore]
UITabBar.appearance().barTintColor = coloree
UITabBar.appearance().tintColor = colore
UITabBar.appearance().translucent = false
self.MessageTable.delegate = self
self.MessageTable.dataSource = self
func refreshPulled() {
loadData()
self.MessageTable.reloadData()
refreshControl.endRefreshing()
}
}
func loadData() {
let query = PFQuery(className: "Messages")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {
(posts: [PFObject]?, error: NSError?) -> Void in
if (error == nil) {
if let posts = posts as [PFObject]? {
for post in posts{
self.Image.append(post["Post"] as! PFFile)
self.Username.append(post["Name"] as! String)
self.Likes.append(post["Vote"] as! Int)
}
}
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.MessageTable.dequeueReusableCellWithIdentifier("cell")! as! TableViewCellHome
var imagesToLoad = self.Image[indexPath.row] as PFFile
var imagesUser = self.Username[indexPath.row] as String
var imageLikes = self.Likes[indexPath.row] as Int
//This line gives me an error: call can throw, but is not marked with 'try' and the error is not handled
var imagesdata = imagesToLoad.getData()
var finalizedImage = UIImage(data: imagesdata)
cell.PostImage.image = finalizedImage
cell.UsernameLabel.text = imagesUser
cell.LikesLabel.text = "\(imageLikes)"
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Username.count
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
This code should get and display Image, string and Int Value from parse's backend. The problem is that nothing is displayed. How can I change the code so that this will display correctly? There is also an error at the line:
var imagesdata = imagesToLoad.getData()
This line tells me
call can throw, but is not marked with 'try' and the error is not handled
Thanks in advance to anyone that can help me solve this problem.

Resources