How to get value from the first 3 rows in TableView using swift? - swift

I retrieve data from MySql via PHP file to get users information and scores to load them in a table. I need to get the value of the first 3 users and put them in a Label outside the Table, it is like game leaders list. I attached an image to explain the idea.
Here is the structure code:
import Foundation
protocol HomeModelProtocol: AnyObject {
func itemsDownloaded(items: NSArray)
}
class HomeModel: NSObject, URLSessionDataDelegate {
weak var delegate: HomeModelProtocol!
let urlPath = "https://mywebsite.com/folder/callUserList.php" //this will be changed to the path where service.php lives
func downloadItems() {
let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Failed to download data")
}else {
print("Data downloaded")
self.parseJSON(data!)
}
}
task.resume()
}
func parseJSON(_ data:Data) {
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
} catch let error as NSError {
print(error)
}
var jsonElement = NSDictionary()
let users = NSMutableArray()
for i in 0 ..< jsonResult.count
{
jsonElement = jsonResult[i] as! NSDictionary
let user = UsersModel()
//the following insures none of the JsonElement values are nil through optional binding
if let name = jsonElement["name"] as? String,
let email = jsonElement["email"] as? String,
let phoneNumber = jsonElement["phone"] as? String,
let userImage = jsonElement["image"] as? String
{
user.name = name
user.email = email
user.phoneNumber = phoneNumber
user.userImage = userImage
}
users.add(user)
}
DispatchQueue.main.async(execute: { () -> Void in
self.delegate.itemsDownloaded(items: users)
})
}
}
Here is the model:
import Foundation
class UsersModel: NSObject {
//properties
var name: String?
var email: String?
var phoneNumber: String?
var userImage: String?
//empty constructor
override init()
{
}
//construct with #name, #address, #latitude, and #longitude parameters
init(name: String, email: String, phoneNumber: String, userImage: String) {
self.name = name
self.email = email
self.phoneNumber = phoneNumber
self.userImage = userImage
}
//prints object's current state
override var description: String {
return "Name: \(String(describing: name)), Email: \(String(describing: email)), Phone Number: \(String(describing: phoneNumber)), User Image: \(String(describing: userImage))"
}
}
Here is the code in the TableView controller:
var feedItems: NSArray = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
let homeModel = HomeModel()
homeModel.delegate = self
homeModel.downloadItems()
}
func itemsDownloaded(items: NSArray) {
feedItems = items
self.listTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of feed items
return feedItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Retrieve cell
let cellIdentifier: String = "BasicCell"
let myCell: WinnerTableCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! WinnerTableCell
// Get the location to be shown
let item: UsersModel = feedItems[indexPath.row] as! UsersModel
// Get references to labels of cell
myCell.lbTextName!.text = item.name
return myCell
}
The data shows in the Table but I have no idea how to fill the 3 label with the 3 first users from the Table.
How can I get these values from the table and pass it to a label in the same ViewController?
Thanks
When adding this code:
if feedItems.count >= 3 {
lblFirstWinner.text = feedItems[0].name // 1st winner
lblSecondWinner.text = feedItems[1].name // 2nd winner
lblThirdWinner.text = feedItems[2].name // 3rd winner
}
it shows error: Value of type 'Any' has no member 'name'

Change itemsDownloaded method as
func itemsDownloaded(items: NSArray) {
feedItems = items
self.listTableView.reloadData()
for (index, user) in items.enumerated() {
let user = user as! UserModel
switch index {
case 0: // 1st winner
lblFirstWinner.text = user.name
case 1: // 2nd winner
lblSecondWinner.text = user.name
case 2: // 3rd winner
lblThirdWinner.text = user.name
}
}
}
OR
Change your HomeModelProtocol method and feedItems type to [UsersModel]
protocol HomeModelProtocol: AnyObject {
func itemsDownloaded(items: [UsersModel]) // Changed
}
var feedItems =[UsersModel]() // Changed
override func viewDidLoad() {
super.viewDidLoad()
let homeModel = HomeModel()
homeModel.delegate = self
homeModel.downloadItems()
}
func itemsDownloaded(items: [UsersModel]) {
feedItems = items
self.listTableView.reloadData()
if feedItems.count >= 3 {
lblFirstWinner.text = feedItems[0].name // 1st winner
lblSecondWinner.text = feedItems[1].name // 2nd winner
lblThirdWinner.text = feedItems[2].name // 3rd winner
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of feed items
return feedItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Retrieve cell
let cellIdentifier: String = "BasicCell"
let myCell: WinnerTableCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! WinnerTableCell
// Get references to labels of cell
myCell.lbTextName!.text = feedItems[indexPath.row].name // Changed
return myCell
}

Just you need to add a few lines in the below function and your solution will be done.
func itemsDownloaded(items: NSArray) {
feedItems = items
self.listTableView.reloadData()
if feedItems.count >= 3 {
lblFirstWinner.text = feedItems[0].name // 1st winner
lblSecondWinner.text = feedItems[1].name // 2nd winner
lblThirdWinner.text = feedItems[2].name // 3rd winner
}
}
Let me know... is it working for you? and please also refer to #vadian comment on your question.

Related

Index out of range when presenting JSON data in tableview

I am having issue identifying and changing the color of tableview rows that contain the same name value in both [ListStruct] which contains the inital data for the tableview rows, and [HighlightStruct] which contains the name that need to be highlighted.
Initially I have the following JSON array populate my tableview:
private func fetchJSON() {
guard let url = URL(string: "www.test.com")
else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "test=test1".data(using: .utf8)
URLSession.shared.dataTask(with: request) { data, _, error in
guard let data = data else { return }
do {
self.structure = try JSONDecoder().decode([ListStruct].self,from:data)
DispatchQueue.main.async {
self.tableView.reloadData()
}}catch {print(error)}}.resume()}
struct ListStruct: Codable {
let id: String
let wo: String
let name: String
let type: String
}
Then the same view controller has a second JSON array that is decoded below for highlighting:
func processJSON(_ json: String) {
do{
let mydata = Data(json.utf8)
let decoded = try JSONDecoder().decode(Set<HighlightStruct>.self,from: mydata)
print(decoded)
} catch {
print(error)
}
}
struct HighlightStruct: Codable, Hashable {
var id: Int
var name: String
}
Applying Highlight
var mySet: Set<HighlightStruct> = []
var highlightedStructure = [HighlightStruct]()
var structure = [ListStruct]()
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! myCell
let portfolio: ListStruct
portfolio = structure[indexPath.row]
let highlight: HighlightStruct
highlight = highlightedStructure[indexPath.row]
//Highlight those that match in both arrays
if highlight.wo == portfolio.wo {
cell.backgroundColor = .yellow
}
Getting index out of range
You are getting index out of range error because your arrays are empty or there is no index that exist in your arrays. Maybe you can check your service call, the arrays could not be filled properly.
Make sure ur two list count is same size, or process data to one list.
You need to handle exceptions when structure does not have same wo to compare.
struct ListStruct: Codable {
let id: String
let wo: String
let name: String
let type: String
let hightlight:HighlightStruct!
}
func processJSON(_ json: String) {
do{
let mydata = Data(json.utf8)
let decoded = try JSONDecoder().decode(Set<HighlightStruct>.self,from: mydata)
print(decoded)
for hl in decoded{
var filter = structure.filter({$0.wo == hl.wo})
filter.hightlight = hl
}
} catch {
print(error)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! myCell
let portfolio: ListStruct
portfolio = structure[indexPath.row]
//Highlight those that match in both arrays
if portfolio.hightlight?.wo == portfolio.wo {
cell.backgroundColor = .yellow
}

Stripe Alamofire JSON not populating array

I am trying to populate a UITableView with a list of credit cards in Stripe. I know it works for my test environment because I am able to see a JSON response from Postman. It for some reason is not populating my table.
Since this is an [Any Object] I do not need to create a separate class with init stings? I have other tables in my app populating data and updated UILabels after pulling info from FireBase.
Here is the code in the PaymentsVC.swift View Controller:
class PaymentVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var headerView: UIView!
#IBOutlet var cardsTableView: UITableView!
#IBOutlet var cardTextField: STPPaymentCardTextField!
var stripeTool = StripeTools()
static let sharedClient = MyAPIClient()
//var customerId: String?
let customerId = "mycusid"
var baseURLString: String? = "https://api.sripe.com/v1/customers"
var baseURL: URL {
if let urlString = self.baseURLString, let url = URL(string: urlString) {
return url
} else {
fatalError()
}
}
var stripeUtil = StripeUtil()
var cards = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
//only one section
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.cards.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let url = self.baseURL.appendingPathComponent("\(self.customerId)/sources?object=card")
let headers = ["Authorization": self.stripeTool.getBasicAuth()]
Alamofire.request(url, headers: headers)
.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result {
case .success(let result):
if let cards = STPCustomer.decodedObject(fromAPIResponse: result as? [String: AnyObject]) {
print(cards)
// completion(cards, nil)
} else {
// completion(nil, NSError.customerDecodingError)
}
case .failure(let error): break
// nil, error
}
}
//get card cell with cardCell identifier don't forget it on your storyboard
let cell = tableView.dequeueReusableCell(withIdentifier: "cardCell") as! CardCell
//get the last4 value on the card json, create the string and pass it to the label
if let last4 = self.cards[indexPath.row]["last4"] {
cell.cardNumberLabel.text = "**** **** **** \(last4!)"
}
//get the month/year expiration values on the card json, create the string and pass it to the label
if let expirationMonth = self.cards[indexPath.row]["exp_month"], let expirationYear = self.cards[indexPath.row]["exp_year"] {
cell.expirationLabel.text = "\(expirationMonth!)/\(expirationYear!)"
}
return cell
}
Don't put api calls inside cellForRowAt as it'll be called every cell creation/dequeuing, you need to put this code inside viewDidLoad , with reloading the table
let url = self.baseURL.appendingPathComponent("\(self.customerId)/sources?object=card")
let headers = ["Authorization": self.stripeTool.getBasicAuth()]
Alamofire.request(url, headers: headers)
.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result {
case .success(let result):
if let cards = STPCustomer.decodedObject(fromAPIResponse: result as? [String: AnyObject]) {
print(cards)
self.cards = cards
self.cardsTableView.reloadData()
// completion(cards, nil)
} else {
// completion(nil, NSError.customerDecodingError)
}
case .failure(let error): break
// nil, error
}
}
don't forget to set in viewDidLoad
self.cardsTableView.delegate = self
self.cardsTableView.dataSource = self

Default value for UITableView Cell if Firebase snapshot is nil

I have looked around and I cannot figure this out.
I am trying to set a default value of a tableView Cell if a Firebase snapshot returns nil
Example:
A snapshot is made to show all the event names from my Firebase Database
in a tableView using a dequeReusableCell.
But if the snapshot returns nil, the tableView returns with 1 cell with a label saying "Sorry, there are no events."
Here is my firebase snapshot code. This code does currently handle if the snapshot does return nil with a print() statement.
func populateTableView(){
let uid = Auth.auth().currentUser?.uid
ref = Database.database().reference()
ref.child("events").child(uid!).child(currentDate).observeSingleEvent(of: .value, with: { (snapshot) in
self.events = []
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {
//print("SNAP: \(snap)")
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let event = Event(postKey: key, postData: postDict)
self.events.append(event)
//print(self.events)
}
}
}
if !snapshot.exists() {
self.eventStatus = false
self.tableView.reloadData()
print("No Event here")
} else {
self.eventStatus = true
self.tableView.reloadData()
}
})
}
The firebase Objects get stored into the Event class and are stored a dictionary. I don't think this code is needed, but here is the event class code for more context.
import Foundation
import Firebase
class Event {
var ref: DatabaseReference!
private var _description: String!
private var _imageUrl: String!
private var _eventTitle: String!
private var _eventType: String!
private var _eventTime: String!
private var _eventStartDate: String!
private var _eventEndDate: String!
private var _monthlyRepeat: String!
private var _weeklyRepeat: String!
private var _eventColor: String!
private var _postKey: String!
private var _postRef: DatabaseReference!
var description: String {
return _description
}
var imageUrl: String {
return _imageUrl
}
var eventTitle: String {
return _eventTitle
}
var eventType: String {
return _eventType
}
var eventTime: String {
return _eventTime
}
var eventStartDate: String {
return _eventStartDate
}
var eventEndDate: String {
return _eventEndDate
}
var monthlyRepeat: String {
return _monthlyRepeat
}
var weeklyRepeat: String {
return _weeklyRepeat
}
var eventColor: String {
return _eventColor
}
var postKey: String {
return _postKey
}
init(postKey: String, postData: Dictionary<String, AnyObject>) {
self._postKey = postKey
if let description = postData["description"] as? String {
self._description = description
}
if let imageUrl = postData["event_Image_URL"] as? String {
self._imageUrl = imageUrl
}
if let eventTitle = postData["event_Title"] as? String {
self._eventTitle = eventTitle
}
if let eventType = postData["event_Type"] as? String {
self._eventType = eventType
}
if let eventTime = postData["event_Time"] as? String {
self._eventTime = eventTime
}
if let eventStartDate = postData["start_Date"] as? String {
self._eventStartDate = eventStartDate
}
if let eventEndDate = postData["end_Date"] as? String {
self._eventEndDate = eventEndDate
}
if let monthlyRepeat = postData["monthly_Repeat"] as? String {
self._monthlyRepeat = monthlyRepeat
}
if let weeklyRepeat = postData["weekly_Repeat"] as? String {
self._weeklyRepeat = weeklyRepeat
}
if let eventColor = postData["color"] as? String {
self._eventColor = eventColor
}
let uid = Auth.auth().currentUser?.uid
ref = Database.database().reference()
let eventRef = ref.child("events").child(uid!).child("Monday May, 29")
_postRef = eventRef.child(_postKey)
}
}
The simplest way to solve this is to add a title UILabel to your ViewcController and change the text when snapshot is not available.
Or if that doesn't work for you for some reason you could try this:
I did not check this, but I might get you on track.
First you will need to change your populateTableView method so that an events array is created even when snapshot has no results. This way the events array count will be 1 (and one row will be added to your tableView) even if snapshot had no result.
populateTableView(){
let uid = Auth.auth().currentUser?.uid
ref = Database.database().reference()
ref.child("events").child(uid!).child(currentDate).observeSingleEvent(of: .value, with: { (snapshot) in
self.events = []
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {
//print("SNAP: \(snap)")
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let event = Event(postKey: key, postData: postDict)
self.events.append(event)
//print(self.events)
}
}
}
else{ // Snapshot does not exist
let postDict: Dictionary<String, AnyObject> // Add an empty Dictionary
let key = -1 // Or what ever value you could not possibly expect
let event = Event(postKey: key, postData: postDict)
self.events.append(event)
self.tableView.reloadData()
print("No Event here")
}
})
}
Notice that when snapshot is not valid or available you add an empty Dictionary with an unique key value to your events array.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.count
}
You need to create two custom cells with unique identifiers.
Now you can "actually" populate your tableView similar to this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let event = events.[indexPath.row]
let conditionKey = event.key
if(conditionKey == -1){ // or whatever value you gave in populateTableView to indicate that snapshot did not exist
let cell = tableView.dequeueReusableCell(withIdentifier: "identifierCellNotSoGood", for: indexPath) as! CustomCellNotSoGood
cell.noSnapShotLabel1.text = "Sorry, there are no events."
return cell
}
else{
let cell = tableView.dequeueReusableCell(withIdentifier: "identifierCellAllGood", for: indexPath) as! CustomCellAllGood
cell.yourCustomLabel1.text = event.key // Or whatever data you are displaying
cell.sourCustomLabel2.text = event.event // Or whatever data you are displaying
return cell
}
return UITableViewCell
}
If you need to handle the selection of a table cell you can do this:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// get rid of the ugly highlighting
tableView.deselectRow(at: indexPath, animated: false)
let event = events.[indexPath.row
let conditionKey = event.key
if(conditionKey == -1){ // or whatever value you gave in populateTableView to indicate that snapshot did not exist
// Do what you need or not
}
else{
// Do something meaningful with your database
doSomething(withEventData: event)
}
}

Remote Data won't show on tableView

I'm clueless as to what is wrong. My console doesn't give me any errors, my code seems fine but nothing is showing up. Could someone check my code, see why it doesn't want to work? My tableView is connected with its delegates and source. Not sure what is the problem.
Here is my code:
private let cellIdentifier = "cell"
private let apiURL = "api link"
class TableView: UITableViewController {
//TableView Outlet
#IBOutlet weak var LegTableView: UITableView!
//API Array
var legislatorArray = [congressClass]()
func getLegislators (fromSession session: NSURLSession) {
//Calling url
if let jsonData = NSURL(string: apiURL) {
// Requesting url
let task = session.dataTaskWithURL(jsonData) {(data, response, error) -> Void in
//Check for errors
if let error = error {print(error)
} else {
if let http = response as? NSHTTPURLResponse {
if http.statusCode == 200 {
//Getting data
if let data = data {
do {
let legislatorData = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
//Get API data
if let getData = legislatorData as? [NSObject:AnyObject],
findObject = getData["results"] as? [AnyObject]{
//Return data
for cellFound in findObject{
if let nextCell = cellFound["results"] as? [NSObject:AnyObject],
name = nextCell["first_name"] as? String,
lastName = nextCell["last_name"] as? String,
title = nextCell["title"] as? String,
partyRep = nextCell["party"] as? String,
position = nextCell ["position"] as? String,
id = nextCell ["bioguide_id"] as? String
{
//Add data to array
let addData = congressClass(name: name, lastName: lastName, title: title, party: partyRep, position: position, bioID: id)
self.legislatorArray.append(addData)
}
}//end cellFound
//Adding data to table
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.tableView.reloadData()
}
}
}
//end do
catch {print(error)}
}//end data
}//end statusCode
}//end http
}//else
}//end task
//Run code
task.resume()
}//end jsonData
}
override func viewDidLoad() {
super.viewDidLoad()
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let urlSession = NSURLSession(configuration: sessionConfig)
getLegislators(fromSession: urlSession)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
//TableView Rows
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return legislatorArray.count
//return 5
}
//Cell Configuration
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CellTableView
cell.lesName?.text = legislatorArray[indexPath.row].name + " " + legislatorArray[indexPath.row].lastName
cell.lesTitle?.text = legislatorArray[indexPath.row].title
cell.lesParty?.text = legislatorArray[indexPath.row].party
//These tests worked fine.. the tableView is working. But the data doesn't seem to pass.
//cell.lesName.text = "Name" + " " + "lastName"
//cell.lesTitle.text = "Title goes here"
//cell.lesParty.text = "D"
return cell
}
}
You're not reloading the tableView
The problem is in this piece of code
//-----------------------------
//New empty array for api data
var indexPath:[NSIndexPath] = []
//Adding data to new array
for i in 0..<self.legislatorArray.count{
let secondIndexPath = NSIndexPath(forRow: i, inSection: 0)
indexPath.append(secondIndexPath)
}
//Adding data to table
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.tableView.insertRowsAtIndexPaths(indexPath, withRowAnimation: .Left)
}
You don't need any of that. You can just reload the tableView as follows:
//Adding data to table
dispatch_async(dispatch_get_main_queue()) { () -> Void in
//You only need to reload it and that should do the trick
self.tableView.reloadData()
}
I know you said your tableView is connected to the delegate and dataSource but it's not showing in your code.
You conformed the ViewController to the correct protocols but you need something like this in your viewDidLoad.
self.tableView.deletage = self
self.tableView.dataSource = self
//I don't know if this was a typo but in your cellForRowAtIndexPath you are using CellTableView
let nibName = UINib(nibName: "CellTableView", bundle:nil)
self.tableView.registerNib(nibName, forCellReuseIdentifier: cellIdentifier)
I created an example of a better design for your implementation
This is for the WebService and your Custom Class
https://github.com/phantomon/Stackoverflow/blob/master/SO1/MyTableView/MyTableView/Models/WebServiceManager.swift
This is for the ViewController with your tableView
https://github.com/phantomon/Stackoverflow/blob/master/SO1/MyTableView/MyTableView/ViewController.swift
You just need to modify the UITableViewCell with your custom one.
And of course review your custom class data.

swift/parse: error when setting Parse data to labels

What I am trying to do is to have data from Parse be retrieved from columns by object order. All labels are connected to their respective outlets and all of the outputs retrieve their correct data.
When I run it and open a cell in the tableview it crashes and gives me Thread 1: EXC_BAD_INSTRUCTION (code=EXC>I386_INVOP, subcode=0x0) on this line: self.navBar.topItem?.title = output1 if I select the first cell, and then on this line: self.navBar.topItem?.title = output1b if I select the second cell.
Here is the full function:
firstObject is grabbing the first object in the "eventsdetail" column
secondObject is grabbing the second object in the "eventsdetail" column
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var query = PFQuery(className: "eventsdetail")
let runkey = query.orderByAscending("ID")
runkey.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error : NSError?) -> Void in
if error == nil {
if let objects = objects as [PFObject]! {
for object in objects {
var firstObject = objects[0]
var secondObject = objects[1]
let output1 = firstObject.objectForKey("navTitle") as! String!
let output2 = firstObject.objectForKey("articleTitle") as! String!
let output3 = firstObject.objectForKey("written") as! String!
let output4 = firstObject.objectForKey("date") as! String!
let output5 = firstObject.objectForKey("article") as! String!
let output1b = secondObject.objectForKey("navTitle") as! String!
let output2b = secondObject.objectForKey("articleTitle") as! String!
let output3b = secondObject.objectForKey("written") as! String!
let output4b = secondObject.objectForKey("date") as! String!
let output5b = secondObject.objectForKey("article") as! String!
if indexPath.row == 0 {
self.performSegueWithIdentifier("0a", sender: nil)
self.tableview.deselectRowAtIndexPath(indexPath, animated: true)
self.navBar.topItem?.title = output1
self.articleTitle.text = output2
self.writtenBy.text = output3
self.date.text = output4
self.article.text = output5
} else if indexPath.row == 1 {
self.performSegueWithIdentifier("0a", sender: nil)
self.tableview.deselectRowAtIndexPath(indexPath, animated: true)
self.navBar.topItem?.title = output1b
self.articleTitle.text = output2b
self.writtenBy.text = output3b
self.date.text = output4b
self.article.text = output5b
}
}
}
}
}
}
If there is an easier way of doing this, please mention it, if not try to just solve this method's problem. I know it isn't the cleanest way of doing things.
I am not sure of how you Parse your data but if it can help you, here's how I would do:
//
// Test.swift
// Test
//
// Created by Charles-Olivier Demers on 16-01-04.
//
import UIKit
//import Parse
class EventViewController: UIViewController, UITableViewDelegate {
private var _info = [EventDetails]()
override func viewDidLoad() {
fetchData()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("0a", sender: nil)
self.tableview.deselectRowAtIndexPath(indexPath, animated: true)
self.navBar.topItem?.title.text = _info[indexPath.row].navTitle()
self.articleTitle.text = _info[indexPath.row].articleTitle()
self.writtenBy.text = _info[indexPath.row].writtenBy()
self.date.text = _info[indexPath.row].date()
self.article.text = _info[indexPath.row].article()
}
func fetchData() {
let query = PFQuery(className: "eventsDetails")
query.orderByAscending("ID")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects {
for object in objects {
let navTitleObject = object["navTitle"] as! String
let articleTitleObject = object["articleTitle"] as! String
let writtenByObject = object["writtenByObject"] as! String
let dateObject = object["dateObject"] as! String
let articleObject = object["articleObject"] as! String
_info.append(EventDetails(navTitle: navTitleObject, articleTitle: articleTitleObject, writtenBy: writtenByObject, date: dateObject, article: articleObject))
}
}
}
else {
print("Error #\(error!.code)")
}
}
}
}
class EventDetails {
private var _navTitle: String!
private var _articleTitle: String!
private var _writtenBy: String!
private var _date: String!
private var _article: String!
init(navTitle: String, articleTitle: String, writtenBy: String, date: String, article: String) {
self._navTitle = navTitle
self._article = articleTitle
self._writtenBy = writtenBy
self._date = date
self._article = article
}
func navTitle() -> String {
return _navTitle
}
func articleTitle() -> String {
return _articleTitle
}
func writtenBy() -> String {
return _writtenBy
}
func date() -> String {
return _date
}
func article() -> String {
return _article
}
}
First of all, I would create a class named EventDetails. This class will take all the property of EventsDetails class on Parse. So when you fetch your data, you append the data you fetch in an array of EventDetails class in Swift.
After that in your
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
you take the value in your EventDetails array with the indexPath.row and you fill your Table View.
That is how I would do.