Print func didn't print all itmes - ios

I have a swift file Data.swift
extension NSDate {
convenience init(dateString: String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "MM/dd/yyyy"
dateStringFormatter.timeZone = NSTimeZone(name: "GMT")
let date = dateStringFormatter.dateFromString(dateString)
self.init(timeInterval:0, sinceDate:date!)
}
func getDatePart() -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
formatter.timeZone = NSTimeZone(name: "GMT")
return formatter.stringFromDate(self)
}
}
class GDate {
let image : String
let name : String
let date: String
init(gImage : String, gName : String, gDate: String) {
self.name = gName
self.image = gImage
self.date = NSDate(dateString: gDate).getDatePart()
}
}
struct Data {
let places = [
GDate(gImage: "image.png", gName: "USA", gDate: "04/26/2016"),
GDate(gImage: "image2.png", gName: "FAR", gDate: "03/26/2016"),
GDate(gImage: "image3.png", gName: "UK", gDate: "02/26/2016"),
GDate(gImage: "image4.png", gName: "GER", gDate: "01/26/2016")
]
}
in the tableView in the "cellForRowAtIndexPath" method
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! GamesViewCell
let gD = Data()
let entry = gD.places[indexPath.row]
let gDate = entry.date
let image = UIImage(named: entry.image)
cell.gameImageView.image = image
cell.gameNameLabel.text = entry.name
print(gDate)
return cell
in the debuger it only print the first and second date and ignore the rest ?!
"same for the names if I used it instead of the dates"
the debuger

Related

extension Date { has no effect

This is my original timestamp code
How should I modify to cite him
How should I modify the code to refer to the "extension Date {" code
func getDatas(){
if let timestamp = document.get("timestamp") as? TimeInterval {
let date = Date(timeIntervalSince1970: timestamp)
let post = Post(email: email, caption: caption, imageUrl: imageURL, date: date)
...
...
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! FeedCell
let post = self.postArray[indexPath.row]
let date = post.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm"
let dateString = dateFormatter.string(from: date)
self.getUserInfo(userEmail: postArray[indexPath.row].email,cell: cell)
cell.captionLabel.text = postArray[indexPath.row].caption
cell.postImage.sd_setImage(with: URL(string: postArray[indexPath.row].imageUrl))
cell.timeLabel.text = dateString
I want to change to the following date display method, but the changes have no effect
extension Date {
static func timeString(timeInterval: TimeInterval) -> String{
let date = getNowDateFromatAnDate(Date(timeIntervalSince1970: timeInterval/1000))
let formatter = DateFormatter()
if date.isToday() {
//是今天
formatter.dateFormat = "今天HH:mm"
return formatter.string(from: date)
}else if date.isYesterday(){
//是昨天
formatter.dateFormat = "昨天HH:mm"
return formatter.string(from: date)
}else if date.isSameWeek(){
//是同一周
let week = date.weekdayStringFromDate()
formatter.dateFormat = "\(week)HH:mm"
return formatter.string(from: date)
}else{
formatter.dateFormat = "yyyy-MM-dd HH:mm"
return formatter.string(from: date)
}
}
...
...
...
...
How should I modify to cite him
The static keyword allow us to attach the method to a class/struct rather than to instances of it.
And since the static func timeString(timeInterval: TimeInterval) -> String in your Date extension returns a string you can replace your Post date: Date variable with timeString: String and then you can access it directly:
if let timestamp = document.get("timestamp") as? TimeInterval {
let timeString = Date.timeString(timeInterval: timestamp)
let post = Post(email: email, caption: caption, imageUrl: imageURL, timeString: timeString)
// ...
}
cell.timeLabel.text = post.timeString

How to format date correctly

How do I format this date so that it is readable. I want it to show for example: "January 7th, 2018 7:30am". I tried to look at other answers but wasn't sure where to add the extension.
let date = Date(timeIntervalSince1970: request.timestamp / 1000)
dateCell.textLabel?.text = date.description
class Request {
var key:String
var sender:String
var recipient:String
var name:String
var location:String
var when:String
var whereStr:String
var message:String
var timestamp:Double
var status:String
init(dict: [String: Any]) {
self.key = dict["key"] as? String ?? ""
self.sender = dict["sender"] as? String ?? ""
self.recipient = dict["recipient"] as? String ?? ""
self.name = dict["name"] as? String ?? ""
self.location = dict["location"] as? String ?? ""
self.when = dict["when"] as? String ?? ""
self.whereStr = dict["where"] as? String ?? ""
self.message = dict["message"] as? String ?? ""
self.timestamp = dict["timestamp"] as? Double ?? 0.0
self.status = dict["status"] as? String ?? ""
}
Try This
func getCurrentDateTimeFromTimeStamp(timeStapm:String)->String{
let date = NSDate(timeIntervalSince1970:Double(timeStapm)!/1000)
let formatter = DateFormatter()
formatter.dateFormat = "MMMM d, yyyy HH:mm a"
return formatter.string(from: date as Date)
}
pass timestamp and get as date in string format as per your requirement just pass dateFormat.
use like this
dateCell.textLabel?.text = self.getCurrentDateTimeFromTimeStamp(timeStapm:"pass your timestamp")
You should use DateFormatter:
let formatter = DateFormatter()
formatter.format = "MMMM d, yyyy HH:mm a"
let dateString = formatter.string(from: date)
Use a dateFormatter object to style the date however you want
let format = DateFormatter()
format.format = "MM/dd/yyyy"
//get your date in string like this
let dateInString = format.string(from: date)
// this will give you "10/02/2018"
You can visit date format examples to see different format and how to get them.
You can add extension anywhere in the app and one (same name) extension for comlpete app. look below
import UIKit
class ViewControllerHellBoy: UIViewController
{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
dateCell.textLabel?.text = self.userFriendlyFullDate()
}
}
extension Date: Dateable {
var formatter: DateFormatter { return DateFormatter() }
/** Return a user friendly hour */
func userFriendlyFullDate() -> String {
// Customize a date formatter
formatter.dateFormat = ""MMMM d, yyyy HH:mm a"" //Use format you want to
formatter.timeZone = TimeZone(abbreviation: "UTC") . // Time zone you wishes to provide
return formatter.string(from: self)
}
That is how you can use extensions. You can also create separate class and keep all extensions there.

Save NSDate and Doubles into Entity (CoreData)

I can get it to work fine using just Strings but if I try to use Doubles or NSDates then I get an error:
"Cannot assign value of type "NSDate?" to type "String?"
"Cannot assign value of type "Double?" to type "String?"
#IBAction func save(_ sender: Any) {
if item != nil {
item?.startdate = startDate.text
item?.pickup = pickup.text
item?.miles = miles.text
item?.company = company.text
item?.destination = destination.text
item?.enddate = endDate.text
} else {
let entitydescription = NSEntityDescription.entity(forEntityName: "Entity", in: pc)
let item = Entity(entity: entitydescription!, insertInto: pc)
item.startdate = startDate.text
item.pickup = pickup.text
item.miles = miles.text
item.company = company.text
item.destination = destination.text
item.enddate = endDate.text
}
do {
try pc.save()
} catch {
print(error)
return
}
navigationController!.popViewController(animated: true)
}
Here is what type each field is:
#NSManaged public var startdate: NSDate?
#NSManaged public var pickup: String?
#NSManaged public var miles: Double
#NSManaged public var company: String?
#NSManaged public var destination: String?
#NSManaged public var enddate: NSDate?
You need to convert miles.text, startdate.text and enddate.text to Double, NSDate and NSDate, respectively.
For startdate.text / enddate.text:
I'm not sure how what limit you have set for these values when the item is saved, but you should use a default value just incase the conversion fails. For this example, assume the dates are formatted "5/15/17" which takes the format M/d/y
let defaultDate = NSDate() //current date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "M/d/y"
if let startDateText = startdate.text, let startDate = dateFormatter.string(from: startDateText) as? NSDate {
item?.startdate = startDate
} else {
item?.startdate = defaultDate
}
if let endDateText = startdate.text, let endDate = dateFormatter.string(from: endDateText) as? NSDate {
item?.startdate = endDate
} else {
item?.startdate = defaultDate
}
For miles.text:
Same idea, use a default value incase the conversion failed based on what the text will be for item.miles
if let milesText = miles.text {
item?.miles = Double(miles.text) ?? 0.0 //default is 0.0
} else {
item?.miles = 0.0
}
or an easy one-liner—
item?.miles = Double(miles.text ?? "0.0")
if there's a specific default value you have in mind, just declare it before you assign the item's property,
let defaultMilesStr = "0.432"
item?.miles = Double(miles.text ?? defaultMiles)
Also, just a tip, it's good practice to not leave optionals wrapped when assigning values. So even though there was check to make sure item != nil, it's overall better to safely unwrap item with a "guard" or "if-let". Since you are creating a new item if one doesn't exist, id go with if-let in this case:
if let item = item {
// assign values to item's prop's
// item.startdate = .....
} else if let entityDescription = NSEntityDescription.entity(forEntityName: "Entity", in: pc), let item = Entity(entity: entityDescription, insertInto: pc) {
// assign values to item's prop's
// item.startdate = .....
}
//further execution
Convert your date string to NSdate then you are able to save that
Try this code i have provide my date string you mat change with your format
let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "MM-dd-yyyy"
Try this :
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
* http://userguide.icu-project.org/formatparse/datetime
*/
let date = dateFormatter.date(from: /* your_date_string */)
and set it as :
item?.date = date
For miles you can use :
if let dMiles = Double(miles.text!) {
item?.miles.text = dMiles
} else {
print("Not a valid Double: \(textField.text!)")
}
Hope it Helps!!

Unable to compare to date[Local date and server date]

I am try to compare two date-
dateArrayForCompare, is the date which i get from NSDate and, dateArrayServer, is the date which i get from json response.
var dateArrayServer = NSMutableArray()
var dateArrayCalendar = NSMutableArray()
var dateArrayForCompare = NSMutableArray()
let dateHomework:NSArray = allAsign.valueForKey("date") as! NSArray
let homeWork = allAsign.valueForKey("assignmenttype") as! NSArray
for date in dateHomework{
self.dateArrayServer.addObject(date as! String)
}
let sys_date = NSDate()
print("System Date: \(sys_date)")
let df = NSDateFormatter()
df.dateFormat = "dd-MM-yyyy"
let currentDate = df.stringFromDate(sys_date)
print("String Date: \(currentDate)")
for dt in 0...self.dateArrayServer.count-1
{
if(self.dateArrayServer.objectAtIndex(dt) .isEqualToString("\(self.dateArrayForCompare)"))
{
print("Assignment on date: \(self.dateArrayServer.objectAtIndex(dt)) are:\n\(allAsign.objectAtIndex(dt))")
}else
{
print("\(self.dateArrayServer.objectAtIndex(dt)) doesn't match with \(self.dateArrayForCompare) ")
}
}
But get this result-
Something like this (swift 2.2)
for dt in 0 ... dateArrayServer.count-1
{
let date1 = dateArrayServer.objectAtIndex(dt) as! String
for value in dateArrayForCompare.enumerate() {
if date1 == value.element as! String {
print(date1)
}
}
}

Swift - How can I get the current time in seconds?

A user posts a comment in a different timezone and another user views the comment in different timezone. The time should be the same when converted back to the users timezone on their device.
Here's what I am trying but getting an "fatal error: unexpectedly found nil while unwrapping an Optional value". The error is happening in my distance time variable when its trying to subtract "time". I printed time before it executed and its saying "nil". Any help please?
import UIKit
class EventCommentCell: UITableViewCell {
var obj : EventCommentObj!
#IBOutlet var profileImage: UIImageView!
#IBOutlet var commentMessage: UITextView!
#IBOutlet var time: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setData(){
profileImage.layer.borderWidth = 1
profileImage.layer.masksToBounds = false
profileImage.layer.borderColor = UIColor(red: 0.125, green: 0.757, blue: 0.569, alpha: 1.0).CGColor
profileImage.layer.cornerRadius = profileImage.frame.height/2
profileImage.clipsToBounds = true
print("The Image URL : \(obj.profileImage)")
ImageLoader.sharedLoader.imageForUrl(obj.profileImage, completionHandler:{(image: UIImage?, url: String) in
self.profileImage.image = image
})
let message = "\(obj.username) \n\(obj.comment)"
let attributedString = NSMutableAttributedString(string: message as String)
let range: NSRange = (message as NSString).rangeOfString(obj.username as String)
let range1: NSRange = (message as NSString).rangeOfString(obj.comment as String)
let font = UIFont.boldSystemFontOfSize(commentMessage.font!.pointSize)
attributedString.addAttribute(NSFontAttributeName, value: font, range: range)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.125, green: 0.757, blue: 0.569, alpha: 1.0), range: range)
commentMessage.attributedText = attributedString
time.text = getCreationTimeInt(obj.created_on)
}
func getCreationTimeInt(dateString : String) -> String{
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
dateFormatter.timeZone = NSTimeZone.systemTimeZone()
let time = dateFormatter.dateFromString(dateString)?.timeIntervalSince1970
let distanceTime = NSDate().timeIntervalSince1970 - time!
let stringTime = returnDistanceTime(distanceTime)
print("**** The time \(stringTime)", terminator: "")
return stringTime
}
func returnDistanceTime(distanceTime : Double) -> String{
var stringTime = ""
if (distanceTime < 0) {
stringTime = "0s"
}else{
if(distanceTime < 60){
stringTime = "\(Int(distanceTime))s"
}else{
if(distanceTime < 3600){
stringTime = "\(Int(distanceTime/60))m"
}else{
if(distanceTime < 3600*24){
stringTime = "\(Int(distanceTime/3600))h"
}else{
if(distanceTime < 3600*24*7) {
stringTime = "\(Int(distanceTime/3600/24))d"
}else{
stringTime = "\(Int(distanceTime/3600/24/7))w"
}
}
}
}
}
return stringTime
}
}
Welcome to stack overflow. I plugged what you had into a Playground and it worked perfectly. Here is what I have:
//: Playground - noun: a place where people can play
import Cocoa
func returnDistanceTime(distanceTime: NSTimeInterval) -> String{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.stringFromDate(NSDate())
}
func getCreationTimeInt(dateString : String) -> String{
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
dateFormatter.timeZone = NSTimeZone.systemTimeZone()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let time = dateFormatter.dateFromString(dateString)?.timeIntervalSince1970
let distanceTime = NSDate().timeIntervalSince1970 - time!
let stringTime = returnDistanceTime(distanceTime)
print("**** The time \(stringTime)", terminator: "")
return stringTime
}
getCreationTimeInt("2016-03-01 12:12:12")
This is an answer from above from Aaron but in Swift 5
func returnDistanceTime(distanceTime: TimeInterval) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.string(from: NSDate() as Date)
}
func getCreationTimeInt(dateString : String) -> String{
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone
dateFormatter.timeZone = NSTimeZone.system
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
let time = dateFormatter.date(from: dateString)?.timeIntervalSince1970
let distanceTime = NSDate().timeIntervalSince1970 - time!
let stringTime = returnDistanceTime(distanceTime: distanceTime)
print("**** The time \(stringTime)", terminator: "")
return stringTime
}

Resources