#nsdateformatter
Explore tagged Tumblr posts
joeyrob1 · 5 years ago
Text
Creating Your First Apple Watch Application
Creating Your First Apple Watch Application
(No Ratings Yet) Loading...
Pham Van Hoang, [email protected], is the author of this article and he contributes to RobustTechHouse Blog
Introduction
At WWDC 2015, watchOS2 for apple watch was made public and it came with a lot of new features and capabilities, including a new ability to write native apps that run right on the watch.
In this article we will show you how to create your first watchOS application named “Stopwatch” using Objective-C. Hooray!
Let’s Get Started
1.     Go to Xcode and create new application. Select watchOS -> Application
2.    Name the app as “Stopwatch”. In this project we don’t need notification so just deselect the option “Include Notification Scene”
3.    Create user interface.
In this Stopwatch app, we will have a label to display our time; a start button to trigger (or stop) the timing; a lap button that allows us to record our last lap time; and a label to display it. To do this, head over to the “Interface.storyboard” in your Watch Kit App and add attributes as below.
“The projects you create for Apple Watch consist of two separate bundles: a Watch app and a WatchKit extension. The Watch app bundle contains the storyboards and resource files associated with all of your app’s user interfaces. The WatchKit extension bundle contains the extension delegate and the controllers for managing those interfaces and for responding to user interactions. While these bundles are distributed inside an iOS app, they are then installed on the user’s Apple Watch and run locally on the watch”  – Apple docs
To have buttons that sit side-by-side of each other, we need to add them into a Group and configure them as below.
4.    Outlets and Actions
The next step we have to take is to link these elements within our app. Go to “InterfaceController.h” class and create outlets and actions as below:
#import <WatchKit/WatchKit.h> #import <Foundation/Foundation.h> @interface InterfaceController : WKInterfaceController { NSTimer *timer; // we use timer to call function update UI every seconds NSDate *startTime; // time that we press start stop watch NSString *currentTimeString; // save current time BOOL isStarted; // check whether the timer is currently running } @property (strong, nonatomic) IBOutlet WKInterfaceLabel *currentTimeLabel; @property (strong, nonatomic) IBOutlet WKInterfaceLabel *lapTimeLabel; @property (strong, nonatomic) IBOutlet WKInterfaceButton *startButton; @property (strong, nonatomic) IBOutlet WKInterfaceButton *lapButton; - (IBAction)lapTimeButtonPress; - (IBAction)startTimeButtonPress; @end
5.    Implement the function.
Now head over to file “InterfaceController.m” to implement codes that actually update time in our watch application.
First we want to add function that update timer every time we call and reset when user press button stop.
- (void) updateTimer { NSDate *dateNow = [NSDate date]; NSTimeInterval interval = [dateNow timeIntervalSinceDate:startTime]; NSDate *timeDate = [NSDate dateWithTimeIntervalSince1970:interval]; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"HH:mm:ss"]; [dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; currentTimeString = [dateFormat stringFromDate:timeDate]; // save current time in stop watch [self.currentTimeLabel setText:currentTimeString]; // update UI } - (void) resetTimer{ // reset timer when user click stop [timer invalidate]; [self.currentTimeLabel setText:@"00:00:00"]; [self.lapTimeLabel setHidden:YES]; }
Next, we need to trigger “update timer” function which update every second using NSTimer. We also need to check whether the timer is currently running or not, so we can disable/enable “lap” button and change the button start title to “stop/start”.
- (IBAction)startTimeButtonPress { isStarted = !isStarted; if (isStarted == YES) { [self.lapButton setEnabled:YES]; [self.startButton setTitle:@"Stop"]; startTime = [NSDate date]; timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES]; } else { [self.lapButton setEnabled:NO]; [self.startButton setTitle:@"Start"]; [self resetTimer]; } }
Lastly, we just need to update “lap” label each time user presses on the “lap” button.
- (IBAction)lapTimeButtonPress { [self.lapTimeLabel setHidden:NO]; self.lapTimeLabel.text = currentTimeString; }
We have now completed a basic stopwatch application. Let’s run the project and enjoy your new apple watch app.
You can find the full example here.  Hope you will find this post useful. If you have any questions, please leave the comments below. Thanks for reading.
Reference
 Apple App Programming Guide for watchOS
Brought to you by the RobustTechHouse team (Singapore based app development company).  If you like our articles, please also check out our Facebook page.
Creating Your First Apple Watch Application was originally published on RobustTechHouse - Mobile App Development Singapore
0 notes
script-ease · 7 years ago
Link
0 notes
vombat · 12 years ago
Text
Date parsing performance on iOS (NSDateFormatter vs sqlite)
Many web services choose to return dates in something other than a unix timestamp (unfortunately).
Recently I set out trying to identify performance bottlenecks with a large import operation in our iOS app. Having tweaked most of the variables, I was surprised to find out that date parsing was actually one of the biggest bottlenecks. The date parsing was done using NSDateFormatter using an ISO-8601 formatted date that looked like this:
2013-09-07T23:45:00Z
That looks simple enough. We had the NSDateFormatter's format setup with a timezone of +0 GMT, and everything was great, expect parsing dates like this was consuming around 20% of the entire import operation. To provide some context, we were testing the import performance by importing roughly 250,000 objects into a SQLite database, and each object had 4 dates associated with it. That meant that we were dealing with a million dates, and parsing a million dates can get expensive.
Almost all of that time was being spent inside NSDateFormatter's dateFromString: method, so there was not much we could do to optimize things ourselves.
The main goal was to get a unix timestamp from the ISO date. Luckily for us, SQLite is quite good at parsing some ISO-8601 dates and works blazingly fast. Here's how SQLite can parse the above date:
sqlite> SELECT strftime("%s", "2013-09-07T23:45:00Z"); 1378597500
Let's convert this to use SQLite's C library.
sqlite3_stmt *statement = NULL; sqlite3_prepare_v2(db, "SELECT strftime('%s', ?);", -1, &statement, NULL); sqlite3_bind_text(statement, 1, [dateString UTF8String], -1, SQLITE_STATIC); sqlite3_step(statement); sqlite3_int64 interval = sqlite3_column_int64(statement, 0); NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
Looks ugly, but we're trying to solve a genuine problem here. So, how did this do in a performance run against NSDateFormatter? About 1400% faster. To parse a million randomly generated dates on an iPhone 5 running iOS 7, NSDateFormatter took a whooping 106.27 seconds, while the SQLite version took just 7.02 seconds.
Here's a link to a gist containing the source code used for this comparison.
If you're curious as to what SQLite is doing under the hood, checkout the date related code in SQLite at http://www.sqlite.org/src/doc/trunk/src/date.c. It mentions that the conversion algorithms it is using are from a book named Astronomical Algorithms by Jean Meeus.
23 notes · View notes
fingertwister · 13 years ago
Text
[snippet] NSDateFormatter string for twitter dates
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat: @"EEE, dd MMM yyyy HH:mm:ss Z"];
6 notes · View notes
ethicalpaul · 11 years ago
Text
NSDateFormatter and empty values
NSDateFormatters are great to use especially in Mac OS X apps because they work so well with Cocoa Bindings in Interface Builder.
There are two kinds of them. One with an OS X 10.0 behavior and one with an OS X 10.4 behavior. iOS uses only the more modern one. In OS X the 10.0 behavior is deprecated and you should use the 10.4 version. But there's a problem.
Let's say you have a text field with a date formatter attached to it in Interface Builder. Now when you run your app, put a date string into the text field and hit enter. So far so good. Then delete the date string and hit enter. It seems that the 10.0 behavior supports this. But the 10.4 behavior complains that it is not a valid date format. So once your text field has a value in it, there's no way to remove that value. Weird!
If you were using an NSNumberFormatter, there is a pair of methods, -setNilSymbol and -nilSymbol, that help you deal with this. You can call [myNumberFormatter setNilSymbol:@""] and then the number formatter will know that if it sees an empty string, it should make the resulting number be nil.
But there is no -nilSymbol for NSDateFormatter. And the weird part is there is almost no mention of this on the internet. How is this possible that more people aren't having to deal with this? Here is about the only mention of it I can find, in a post about NSNumberFormatter:
http://osdir.com/ml/cocoa-dev/2009-08/msg01350.html
Note at the very bottom of the mailing list post, the respondent makes a comment about how it's too bad that NSDateFormatter doesn't have that attribute.
So what is the solution? There is a project on github that adds -setNilSymbol to NSDateFormatter. It's https://github.com/oriontransfer/SWApplicationSupport
You can go a little simpler and just create a subclass of NSDateFormatter that will allow an empty string to be converted to a nil date like this:
@implementation EPDateFormatter /** It is INSANE that NSDateFormatter doesn't allow empty values to resolve to a nil date!!!. */ - (BOOL)getObjectValue:(out id *)obj forString:(NSString *)string errorDescription:(out NSString **)error { BOOL result = [super getObjectValue:obj forString:string errorDescription:error]; if (result == NO && [string length] == 0) { *obj = nil; result = YES; } return result; } @end
I can't find any better way to deal with this. I'm going to create a bug report for this functionality to be built into NSDateFormatter.
1 note · View note
alldonegoodbye · 10 years ago
Link
Also
https://nshipster.com/formatter/
https://waracle.com/blog/iphone/iphone-nsdateformatter-date-formatting-table/
0 notes
idrawcode · 10 years ago
Text
Expensive
A hiatus would be an understatement. Sincere apologies for my inactiveness. =S
Anyway, today's post is going to be really short, but I would say really useful. Just the kind of thing that I like. 
We have all heard about the term "expensive" in programming. Some of us don't really know what it means, but we all know it's bad! The term "expensive" appears in iOS development too. One of the most prominent example would be NSDateFormatter.  So, how do we overcome this issue? Referring to NSDateFormatter case, since it is most likely we are going to use the same date format in the entire app, wouldn't it be better to just create and set the date format just once? That sounds about right, but how do we do it? One way to do so is by using GCD, in particular dispatch_once. By using dispatch_once, we can create a singleton of NSDateFormatter to be called at appropriate places. A singleton is a design pattern in programming where we restrict the instantiation of a class to an object. By using dispatch_once, we ensure that our code is only run ONCE.  How hard is it? Not at all, take a look at the sample code below:
-(NSDateFormatter*)formatter {    static NSDateFormatter *formatter;    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        formatter = [NSDateFormatter new];        formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";    });    return formatter; }
fBam! There you have it, now when you go ahead and call self.formatter in that particular class, it already takes the date format that you have set. Viola! Expensive no more! =]
Happy Coding!
0 notes
sevennet-blog · 11 years ago
Text
How to: NSDate and NSDateFormatter - short format date and time in iphone sdk
How to: NSDate and NSDateFormatter – short format date and time in iphone sdk
NSDate and NSDateFormatter – short format date and time in iphone sdk
Searched for answers, but the ones i found didn’t seem to be iPhone specific.
I basically need to get current date and time separately, formatted as:
2009-04-26 11:06:54
Edit:
The code below,from another question on the same topic, generates
now: |2009-06-01 23:18:23 +0100| dateString: |Jun 01, 2009 23:18| parsed:…
View On WordPress
0 notes
vinnycoyne · 12 years ago
Link
Many web services choose to return dates in something other than a unix timestamp (unfortunately). [...] Luckily for us, SQLite is quite good at parsing some ISO-8601 dates and works blazingly fast. 
Very handy tip. Works about "1400% faster" than NSDateFormatter, according to the tests in the post.
0 notes
tonymillion-blog · 12 years ago
Text
Parsing python datetime isoformat using NSDateFormatter REDUX
So since my last post about parsing python datetime.isoformat using NSDateFormatter I’ve discovered a lot more about the intricacies of doing it successfully, and heres what I’ve gleaned:
First: When there is no microseconds in the datetime isoformat() wont print it
Second: if the microseconds aren’t included in the output, the previous code I posted wont parse it (it’ll return a nil date).
The fixed code:
NSString * inputDate = @"2012-07-19T08:31:23Z"; NSDate * parsedDate = nil; NSDateFormatter *dateFormatter = [NSDateFormatter new]; [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSSSS"]; dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; parsedDate = [dateFormatter dateFromString:inputDate]; if (parsedDate==nil) { NSDateFormatter *iso8601Formatter = [NSDateFormatter new]; [iso8601Formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; iso8601Formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; iso8601Formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; parsedDate = [iso8601Formatter dateFromString:inputDate]; }
This code will “nicely” fail over and use a non-microsecond parser.
BUT WAIT THERES MORE
If you don’t actually need the microsecond accuracy then theres a “better” way to do this, from the python side. Anywhere you are outputting a datetime do the following:
output_ts = str(dt.replace(microsecond = 0).isoformat())+"Z"
(where dt is our datetime object). 
This has the advantage of making sure that all datetimes are “iso8601 compatible”. To decode it use the following code (taken from the code above)
NSDateFormatter *iso8601Formatter = [NSDateFormatter new]; [iso8601Formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; iso8601Formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; iso8601Formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; parsedDate = [iso8601Formatter dateFromString:inputDate];
** its bad-form to allocate a NSDateFormatter each time, it has a fairly hefty setup overhead, you should allocate it in your instance init.
And in summation
If you need to include microseconds in your output, you would be better off outputting it as a float in the format seconds.microseconds and parsing it using [NSDate dateWithTimeIntervalSince1970:] which supports floating point NSTimeInterval input.
To output a float from a datetime (dt) in Python:
import mktime sec_ms = mktime(dt.timetuple()) + dt.microsecond/1000000.0
0 notes
jaytrixz-dev · 12 years ago
Text
Preventing Crash for 12 and 24 Hour Time Formats
In one of my projects, I encountered a bug that involves time formatting and this code has fixed it for me:
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease];
0 notes
alldonegoodbye · 13 years ago
Text
NSDateFormatter Cheat Sheet
Tons of goodies
month M 1..2 09 Month – Use one or two for the numerical month, three for the abbreviation, or four for the full name, or five for the narrow name. 3 Sept 4 September 5 S
0 notes