__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0] swift - uitableview

I have error __NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0] when I try to add second item with the same date.
I can't find where is the issue. I think problem is in getSectionItems function.
Someone can help me?
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var sumLabel: UILabel!
var costItems: NSMutableArray = NSMutableArray()
var accountIdentifier: NSString = NSString()
var costsSum:Int!
var sectionsInTable = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
costsSum = getCostsSum()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
loadData()
self.tableView.reloadData()
costsSum = getCostsSum()
}
func loadData() {
costItems.removeAllObjects()
let moc:NSManagedObjectContext = SwiftCoreDataHelper.managedObjectContext()
let predicate: NSPredicate = NSPredicate(format: "identifier == '\(accountIdentifier)'")!
let results:NSArray = SwiftCoreDataHelper.fetchEntities(NSStringFromClass(Cost), withPredicate: predicate, managedObjectContext: moc)
for cost in results{
let singleCost:Cost = cost as Cost
let costDict:NSDictionary = ["identifier":singleCost.identifier,"costName":singleCost.costName, "costValue":singleCost.costValue, "date":singleCost.date]
costItems.addObject(costDict)
// Date
let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMMM"
let dateString: NSString = dateFormatter.stringFromDate(costDict.objectForKey("date") as NSDate)
let sections: NSSet = NSSet(array: sectionsInTable)
if !sections.containsObject(dateString) {
sectionsInTable.append(dateString)
}
}
self.tableView.reloadData()
}
func getSectionItems(section: Int) -> [Cost] {
var sectionItems = [Cost]()
let moc:NSManagedObjectContext = SwiftCoreDataHelper.managedObjectContext()
let predicate: NSPredicate = NSPredicate(format: "identifier == '\(accountIdentifier)'")!
let results:NSArray = SwiftCoreDataHelper.fetchEntities(NSStringFromClass(Cost), withPredicate: predicate, managedObjectContext: moc)
for cost in results {
let singleCost:Cost = cost as Cost
let costDict:NSDictionary = ["identifier":singleCost.identifier,"costName":singleCost.costName, "costValue":singleCost.costValue, "date":singleCost.date]
let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMMM"
let dateString: NSString = dateFormatter.stringFromDate(costDict.objectForKey("date") as NSDate)
if dateString == sectionsInTable[section] as NSString {
sectionItems.append(singleCost)
}
}
return sectionItems
}
// UITableViewDataSource
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionsInTable[section]
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sectionsInTable.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.getSectionItems(section).count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:DetailTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as DetailTableViewCell
let costDict:NSDictionary = costItems.objectAtIndex(indexPath.row) as NSDictionary
let costName = costDict.objectForKey("costName") as String
let costValue = costDict.objectForKey("costValue") as Double
cell.nazwaWydatkuLabel.text = costName
// Date
let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMMM"
let dateString: NSString = dateFormatter.stringFromDate(costDict.objectForKey("date") as NSDate)
cell.dateLabel.text = dateString
if (Int(costValue)) < 0 {
cell.wartośćLabel.layer.cornerRadius = 8.0
cell.wartośćLabel.layer.masksToBounds = true
cell.wartośćLabel.backgroundColor = UIColor(red: 255.0/255.0, green: 59.0/255, blue: 48.0/255.0, alpha: 1.0)
} else {
cell.wartośćLabel.layer.cornerRadius = 8.0
cell.wartośćLabel.layer.masksToBounds = true
cell.wartośćLabel.backgroundColor = UIColor(red: 127.0/255.0, green: 207.0/255.0, blue: 77.0/255.0, alpha: 1.0)
}
cell.wartośćLabel.text = " \(Int(costValue)) zł "
return cell
}
#IBAction func addCostButtonPressed(sender: UIBarButtonItem) {
self.performSegueWithIdentifier("addCostVC", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "addCostVC" {
let addCostVC: AddTableViewController = segue.destinationViewController as AddTableViewController
let thisID = accountIdentifier
addCostVC.accountIdentifier = thisID
}
}
func getCostsSum() -> Int {
let moc:NSManagedObjectContext = SwiftCoreDataHelper.managedObjectContext()
let predicate: NSPredicate = NSPredicate(format: "identifier == '\(accountIdentifier)'")!
let results:NSArray = SwiftCoreDataHelper.fetchEntities(NSStringFromClass(Cost), withPredicate: predicate, managedObjectContext: moc)
var costSum: Int = 0
for res in results {
var costCount = res.valueForKey("costValue") as Int
costSum += costCount
}
self.sumLabel.text = "\(costSum) zł"
return costSum
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let moc:NSManagedObjectContext = SwiftCoreDataHelper.managedObjectContext()
let results:NSArray = SwiftCoreDataHelper.fetchEntities(NSStringFromClass(Cost), withPredicate: nil, managedObjectContext: moc)
let thisCost: AnyObject = results.objectAtIndex(indexPath.row)
moc.deleteObject(thisCost as NSManagedObject)
//costsValues = getAccountCountSum()
SwiftCoreDataHelper.saveManagedObjectContext(moc)
loadData()
getCostsSum()
self.tableView.reloadData()
}

Related

Tableview array is not loaded properly in iOS Swift?

I'm working in a chat application. Saving sender and receiver messages to firebase. My issue when tried to load array message to TableView, messages are not completely loaded. it shows gap for remaining messages.
MainChatViewController.swift
var messages = [Message]()
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("message count::\(messages.count)")
let message = messages[indexPath.row]
if let cell = chatTableView.dequeueReusableCell(withIdentifier: "Message") as? mainChatScreenTableViewCell {
cell.tag = indexPath.row
cell.configCell(message: message)
return cell
} else {
return mainChatScreenTableViewCell()
}
}
func loadData() {
Database.database().reference().child("messages").child(messageId)
.observe(.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
self.messages.removeAll()
for data in snapshot {
if let postDict = data.value as? Dictionary<String, AnyObject>
{
let key = data.key
let post = Message(messageKey: key, postData: postDict)
self.messages.append(post)
}
}
}
self.chatTableView.reloadData()
})
}//loadData
func moveToBottom() {
DispatchQueue.main.async {
if self.messages.count > 0 {
let indexPath = IndexPath(row: self.messages.count - 1, section: 0)
self.chatTableView.scrollToRow(at: indexPath, at: .bottom, animated: false)
}
}
}
mainChatScreenTableViewCell
import UIKit
import SwiftKeychainWrapper
import Firebase
import FirebaseStorage
import FirebaseDatabase
class mainChatScreenTableViewCell: UITableViewCell {
#IBOutlet weak var recievedMessageLbl: UILabel!
#IBOutlet weak var recievedMessageView: UIView!
#IBOutlet weak var sentMessageLbl: UILabel!
#IBOutlet weak var sentMessageView: UIView!
#IBOutlet var receivedTimeLabel: UILabel!
#IBOutlet var sentTimeLabel: UILabel!
#IBOutlet var likeOrUnlikeImageView: UIImageView!
#IBOutlet var errorImageView: UIImageView!
#IBOutlet var checkImage: UIImageView!
var message: Message!
var currentUser = KeychainWrapper.standard.string(forKey: "uid")
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
sentMessageView.layer.masksToBounds = true
recievedMessageView.layer.masksToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configCell(message: Message) {
self.message = message
print("message label::\(message.message.count)")
if message.sender == currentUser {
let time = message.receivedTimeStamp
let timeinterval : TimeInterval = time
let dateFromServer = NSDate(timeIntervalSince1970:timeinterval)
let formatter = DateFormatter()
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.ISO8601) as Calendar?
formatter.locale = NSLocale(localeIdentifier: "en_IN") as Locale
formatter.timeZone = NSTimeZone(name: "GMT+5:30") as TimeZone?
formatter.dateFormat = "h:mm a"
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
let dateString: String = formatter.string(from: dateFromServer as Date)
print("dateString:::\(dateString)")
sentMessageView.isHidden = false
sentMessageView.layer.backgroundColor = UIColor.clear.cgColor
sentMessageLbl.text = " " + message.message
sentTimeLabel.text = " " + dateString
recievedMessageLbl.text = ""
recievedMessageLbl.isHidden = true
recievedMessageView.isHidden = true
} else {
let time = message.receivedTimeStamp
let timeinterval : TimeInterval = time
let dateFromServer = NSDate(timeIntervalSince1970:timeinterval)
let formatter = DateFormatter()
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.ISO8601) as Calendar?
formatter.locale = NSLocale(localeIdentifier: "en_IN") as Locale
formatter.timeZone = NSTimeZone(name: "GMT+5:30") as TimeZone?
formatter.dateFormat = "h:mm a"
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
let dateString: String = formatter.string(from: dateFromServer as Date)
print("dateString:::\(dateString)")
sentMessageView.isHidden = true
sentMessageLbl.isHidden = true
sentMessageLbl.text = ""
recievedMessageLbl.text = " " + message.message
receivedTimeLabel.text = " " + dateString
recievedMessageLbl.isHidden = false
recievedMessageView.layer.backgroundColor = UIColor.clear.cgColor
}
}
}
Here is my screenshot:
I'm getting correct message count but messages are fully loaded.
Any help much appreciated pls...
use it. heightForRowAt for height of cell but you must check your constraint.
and also use UITableViewDelegate to use it
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}

How to save Tomorrow date tasks in core data and how to get these tasks into table view in Swift?

How to save Tomorrow date tasks in core data and how to get these tasks into table view in Swift ?
When i print("Objects are in Tomorrow Task : (filterTomorrowTask.count)"), then it shows nil array.
I dont know how to fix this bug. I am new to Swift, so dont know how to fix this issue.
Utility Class :
class FilteredData
{
static func filterTomorrowTask(filteredObject: String) -> [Task]
{
let fetchRequest: NSFetchRequest<Task> = Task.fetchRequest()
var user: [Task]? = nil
let predicate = NSPredicate(format: "date_from == %#", filteredObject)
fetchRequest.predicate = predicate
do {
user = try context.fetch(fetchRequest)
return user!
}
catch {
return user!
}
}
}
ViewController.h
//CoreData Object
var filterTomorrowTask: [Task] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tomorrowFilterTask()
self.tblToday.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if tableView == self.tblTomorrow
{
print("Tomorrow Count \(filterTomorrowTask.count)")
return filterTomorrowTask.count
}
else
{
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
if tableView == self.tblTomorrow
{
let cell = tableView.dequeueReusableCell(withIdentifier: "TomorrowTaskCell", for: indexPath) as! TomorrowTaskTVCell
let filteredResult = filterTomorrowTask[indexPath.row]
cell.lblTask.text = filteredResult.task_name
cell.tfTime.text = filteredResult.time_from
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "TomorrowTaskCell", for: indexPath) as! TomorrowTaskTVCell
return cell
}
}
func tomorrowFilterTask()
{
isTomorrow = true
//Adding 1 to Current Date
let today = Date()
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.dateFormat = "yyyy-MM-dd"
let strTomorrow = formatter.string(from: tomorrow!)
filterTomorrowTask = FilteredData.filterTomorrowTask(filteredObject: strTomorrow)
}
You can Try using Func as Below Once
class FilteredData
{
static func filterTomorrowTask(filteredObject: String) -> [Task]
{
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Your Entity Name")
var user: [Task]? = nil
let predicate = NSPredicate(format: "date_from == %#", filteredObject)
fetchRequest.predicate = predicate
do {
user = try context.fetch(fetchRequest)
return user!
}
catch {
return user!
}
}
}
or just simply Without Creating a Special Instance of User
class FilteredData
{
static func filterTomorrowTask(filteredObject: String) -> [Task]
{
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Your Entity Name")
let predicate = NSPredicate(format: "date_from == %#", filteredObject)
fetchRequest.predicate = predicate
///Handler
do
{
let response = try context.fetch(fetchRequest)
return response as! [Audio]
}
catch let error as NSError
{
///failure
print(error)
return [Audio]()
}
}
}

Swift refresh table view

i have a problem,when i called the viewWillAppear ,table view get refreshed,but the data are strange(i insert a new record so i need to refresh the table view every time it appears), for example
original data:a,b,c
insert one record should be:a,b,c,d
result:a,b,c,a(why a?)
Hope someone could help me ,please.
import UIKit
import SQLite
class DetailViewController: UIViewController, UITableViewDelegate,
UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
let inputDetailTable = Table("input_detail")
var labelOneArray = [String]()
var labelTwoArray = [NSAttributedString]()
var labelThreeArray = [String]()
var labelFourArray = [String]()
let id = Expression<Int>("id")
let deleteFlag = Expression<Int>("delete_flag")
// var selectedDatas :AnySequence<Row>!
let viewService = ViewService()
override func viewDidLoad() {
super.viewDidLoad()
getTableViewData()
}
override func viewWillAppear(_ animated: Bool) {
getTableViewData()
self.tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
let selectedDatas = viewService.selectTableData()
var counter = 0
for _ in selectedDatas{
counter += 1
}
return counter
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",
for: indexPath) as! DetailTableViewCell
cell.labelOne.attributedText = labelTwoArray[indexPath.row]
cell.labelTwo.text = labelFourArray[indexPath.row]
return cell
}
func getTableViewData() {
let selectedDatas = viewService.selectTableData()
for selectedData in selectedDatas{
var tempAmount = String(selectedData[Expression<Int>
("amount")])
var tempTwoAmout :NSAttributedString?
if selectedData[Expression<Int>("type_flag")] == 0 {
tempAmount = "-"+tempAmount
let text = tempAmount
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let myMutableString = NSMutableAttributedString(
string: tempAmount,
attributes: [:])
myMutableString.addAttribute(
NSAttributedStringKey.foregroundColor,
value: UIColor.red,
range: textRange)
tempTwoAmout = myMutableString
} else {
tempAmount = "+"+tempAmount
let text = tempAmount
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let myMutableString = NSMutableAttributedString(
string: tempAmount,
attributes: [:])
myMutableString.addAttribute(
NSAttributedStringKey.foregroundColor,
value: UIColor.green,
range: textRange)
tempTwoAmout = myMutableString
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let createTimeFormat = formatter.string(from:
selectedData[Expression<Date>("create_time")])
self.labelOneArray.append(String(selectedData[Expression<Int>
("id")]))
self.labelTwoArray.append(tempTwoAmout!)
self.labelThreeArray.append(String(selectedData[Expression<String>
("location")]))
self.labelFourArray.append(createTimeFormat)
}
}
}
You are calling twice getTableViewData(), and try to remove all data from your arrays before getting new data.

How to insert the first new row in TableViewCell(swift)?

People tell me how to get out of my position and do so that when a new event is added it becomes the beginning, not the end.I will be very grateful for the help.
I have three arrays and I had to sort them out by the parent cells, and in this line I very much played func tableView (_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
import UIKit
import Parse
class PrognozSegmentViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var soccerString = [Soccer]()
var basketString = [Basketball]()
var tennisString = [Tennis]()
var refresh : UIRefreshControl!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var segmentControl: UISegmentedControl!
#IBAction func btnSegment(_ sender: Any) {
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
refresh = UIRefreshControl()
refresh.attributedTitle = NSAttributedString(string: "Потяните вниз чтоб обновить ресурс")
refresh.tintColor = UIColor.green
refresh.addTarget(self, action: #selector(PrognozSegmentViewController.refreshing), for: UIControlEvents.valueChanged)
tableView.addSubview(refresh)
setupSeg()
tableView.tableFooterView = UIView()
tableView.estimatedRowHeight = 88
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = UITableViewCellSeparatorStyle.none
tableView.register(UINib(nibName:"TableViewCell",bundle:nil), forCellReuseIdentifier: "sportCell")
loadObjects1()
loadObjects2()
loadObjects3()
}
func setupSeg() {
let attributes = [ NSAttributedStringKey.foregroundColor : UIColor.yellow,
NSAttributedStringKey.font : UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.bold)];
let attributesSelected = [ NSAttributedStringKey.foregroundColor : UIColor.black,
NSAttributedStringKey.font : UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.bold)];
segmentControl.setTitleTextAttributes(attributes, for: UIControlState.normal)
segmentControl.setTitleTextAttributes(attributesSelected, for: UIControlState.selected)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var returnSport = 0
switch (segmentControl.selectedSegmentIndex) {
case 0 :
returnSport = soccerString.count
break
case 1 :
returnSport = basketString.count
break
case 2 :
returnSport = tennisString.count
break
default :
break
}
return returnSport
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let sportCell = tableView.dequeueReusableCell(withIdentifier: "sportCell", for: indexPath) as! TableViewCell
switch (segmentControl.selectedSegmentIndex) {
case 0 :
let soccer = soccerString[indexPath.row]
sportCell.matchLabel.text = soccer.matchS
soccerString[indexPath.row].imagePrS.getDataInBackground {(data, error) in
sportCell.imageMatch.image = error == nil ? UIImage(data: data!) : nil
}
break
case 1 :
let basket = basketString[indexPath.row]
sportCell.matchLabel.text = basket.matchB
basketString[indexPath.row].imagePrB.getDataInBackground {(data, error) in
sportCell.imageMatch.image = error == nil ? UIImage(data: data!) : nil
}
break
case 2:
sportCell.matchLabel.text = tennisString[indexPath.row].matchT
tennisString[indexPath.row].imagePrT.getDataInBackground {(data, error) in
sportCell.imageMatch.image = error == nil ? UIImage(data: data!) : nil
}
break
default:
break
}
sportCell.selectionStyle = UITableViewCellSelectionStyle.none
let date = Date()
let calendar = Calendar.current
let yesterday = calendar.date(byAdding: .day, value: -1, to: date)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM:d, yyyy"
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
dateFormatter.locale = Locale(identifier: "ru_UA")
dateFormatter.doesRelativeDateFormatting = true
let dataFormater2 = DateFormatter()
dataFormater2.dateFormat = "EEEE, MMM:d, yyyy"
dataFormater2.dateStyle = .short
dataFormater2.timeStyle = .short
dataFormater2.locale = Locale(identifier: "ru_UA")
dataFormater2.doesRelativeDateFormatting = true
sportCell.dataSave.text! = dateFormatter.string(from: date)
sportCell.dataSave.text = dateFormatter.string(from: yesterday!)
return sportCell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func loadObjects1() {
let query = Soccer.query() as! PFQuery<Soccer>
query.findObjectsInBackground { (objects, error) in
if error == nil {
self.soccerString.removeAll()
self.soccerString = objects!
self.tableView.reloadData()
} else {
print(error!)
}
}
}
func loadObjects2() {
let query = Basketball.query() as! PFQuery<Basketball>
query.findObjectsInBackground { (objects, error) in
if error == nil {
self.basketString.removeAll()
self.basketString = objects!
self.tableView.reloadData()
} else {
print(error!)
}
}
}
func loadObjects3() {
let query = Tennis.query() as! PFQuery<Tennis>
query.findObjectsInBackground { (objects, error) in
if error == nil {
self.tennisString.removeAll()
self.tennisString = objects!
self.tableView.reloadData()
} else {
print(error!)
}
}
}
#objc func refreshing() {
loadObjects1()
loadObjects2()
loadObjects3()
tableView.reloadData()
refresh.endRefreshing()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch (segmentControl.selectedSegmentIndex) {
case 0 :
if segue.identifier == "showSoccer" {
if let indexPath = tableView.indexPathForSelectedRow {
let destationViewController = segue.destination as! DetailSoccerTableViewController
destationViewController.detailSoccer = self.soccerString[indexPath.row]
}
}
case 1 :
if segue.identifier == "showBasket" {
let dvc = segue.destination as! DetailBasketViewController
if let indexPath = tableView.indexPathForSelectedRow {
let row = Int(indexPath.row)
dvc.baskets = basketString[row]
}
}
case 2 :
let destationVC: DetailTennisViewController = segue.destination as! DetailTennisViewController
if let indexPath = self.tableView.indexPathForSelectedRow {
let row = Int(indexPath.row)
destationVC.tenises = tennisString[row]
}
self.present(destationVC, animated: true, completion: nil)
default :
break
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch ( segmentControl.selectedSegmentIndex) {
case 0 :
let soccer = soccerString[indexPath.row]
performSegue(withIdentifier: "showSoccer", sender: soccer)
break
case 1 :
let basket = basketString[indexPath.row]
let destinationVC = DetailBasketViewController()
destinationVC.baskets = basket
self.performSegue(withIdentifier: "showBasket", sender: self)
break
case 2 :
let tennis = tennisString[indexPath.row]
let destTenVC = DetailTennisViewController()
destTenVC.tenises = tennis
self.performSegue(withIdentifier: "showTennis", sender: self)
break
default :
break
}
}
}
If your problem is the new object becomes the last
I assume you're talking about an array and you're doing
array.append(item)
If you want to have the item at the beginning do:
array.insert(item, at: 0)
And then
tableView.reloadData()

Getting date from parse and displaying to a string Swift

So like the title says I am getting information from parse and displaying it but i can't figure out how to do this with a date. I need to cover it to a String to display in a label. Ive done a bit or research and understand I will need to use a date formatter but What I don't understand is where I put it and once its formatted how i display it. Any help would be much appreciated!
var names = [String]()
var locations = [String]()
var dates = [NSDate]()
var imageFiles = [PFFile]()
var abouts = [String]()
override func viewDidLoad() {
super.viewDidLoad()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint, error) -> Void in
if let geoPoint = geoPoint {
PFUser.currentUser()?["location"] = geoPoint
PFUser.currentUser()?.saveInBackground()
var getLocalPostsQuery = PFQuery(className: "publicPosts")
if let latitude = PFUser.currentUser()!["location"].latitude {
if let longitude = PFUser.currentUser()!["location"].longitude {
getLocalPostsQuery.whereKey("searchLocation", withinGeoBoxFromSouthwest: PFGeoPoint(latitude: latitude - 0.5, longitude: longitude - 0.5), toNortheast: PFGeoPoint(latitude: latitude + 0.5, longitude: longitude + 0.5))
getLocalPostsQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
self.names.removeAll(keepCapacity: true)
self.locations.removeAll(keepCapacity: true)
self.abouts.removeAll(keepCapacity: true)
self.dates.removeAll(keepCapacity: true)
self.imageFiles.removeAll(keepCapacity: true)
for object in objects {
self.names.append(object["name"] as! String)
self.locations.append(object["location"] as! String)
self.dates.append(object["date"] as! String)
self.abouts.append(object["about"] as! String)
self.imageFiles.append(object["imageFile"] as! PFFile)
//self.attendings.append(object["attending"].count)
self.tableView.reloadData()
}
}
}
}
}
}
}
}
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
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return names.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let LECell = tableView.dequeueReusableCellWithIdentifier("LocalPostsCell", forIndexPath: indexPath) as! LocalPostsTableViewCell
imageFiles[indexPath.row].getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
LECell.postImage.image = downloadedImage
}
}
LECell.postName.text = names[indexPath.row]
LECell.postLocation.text = locations[indexPath.row]
LECell.postDate.text = dates[indexPath.row]
return LECell
}
let localPostsDetailSegue = "showLocalPostsDetailView"
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == localPostsDetailSegue {
let detailScene = segue.destinationViewController as! LocalPostsDetailViewController
if let indexPath = self.tableView.indexPathForSelectedRow {
let row = Int(indexPath.row)
detailScene.name = names[row]
detailScene.location = locations[row]
detailScene.date = dates[row]
detailScene.about = abouts[row]
detailScene.photo = imageFiles[row]
}
}
}
}
You can easily get string from NSDate and show it.
func getStringFromDate(date:NSDate)->String{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yy, H:mm"
return dateFormatter.stringFromDate(yourDate) // yourDate is your parse date
}
you can make a category too.
Swift 3:
func getFormattedDate(string: String) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +zzzz" // 2017-04-20T09:40:30+0000
let formateDate = dateFormatter.date(from: string)!
dateFormatter.dateFormat = "dd-MM-yyyy"
return dateFormatter.string(from: formateDate)
}
let CreatedDates = "\(Date.getFormattedDate(string: "\(records["creationDate"]!)"))"
print("Date : \(CreatedDates)")
//OutPut
20-04-2017

Resources