I am currently at the point to where I want to create a simple text file, read it into my application, convert the string "0700 1300" to an NSDate format to be read into my native calendar.
I am pretty new to objective-c but I am trying to read in both 0700 into the start time of an event and 1300 into the end time of an event. I just cant get the 1300. Mainly I want to store the first WORD "0700" and the second WORD "1300".
EDIT:
If possible please include code that converts the string "0700 1400" to a string will later be the time interval of
EKEvent *myEvent;
This is the code I use to store the data within the text file I'm downloading from the web.
NSData *data = [[NSData alloc] initWithData:downloadFile.receivedData];
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
[self.myDataArray addObject:dataString];
myDataArray is a mutable array which I initiated earlier in viewDidLoad of my current view controller.
This is a small snippet of the textfile im reading in.
Sunday
0 1200
Sunday
2100 2400
Monday
0 600
I was able to parse my text file but now the issue of converting the string that contains the start date and end date to an NSDATE.
I am not looping through the entire file yet, just one line within the specific file, i'll loop through the entire file once I can format ONE line at least.
I currently have converted 0 and 1200 to 2013-06-08 00:00:00 +0000 and 2013-06-08 12:00:00 +0000 by appending and inserting.
Heres the code I used.
NSData *data = [[NSData alloc] initWithData:downloadFile.receivedData];
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSArray *components = [dataString componentsSeparatedByString:#"\n"];
NSString *anotherString = [NSString stringWithFormat:components[1]];
NSArray *times = [anotherString componentsSeparatedByString:#" "];
NSMutableString *startDate = [[NSMutableString alloc] initWithString:times[0]];
NSMutableString *endDate = [[NSMutableString alloc] initWithString:times[1]];
for (int i = startDate.length; i < 4; i++)
[startDate appendString:#"0"];
[startDate appendString:#":00 +0000"];
for (int i = endDate.length; i < 4; i++)
[endDate appendString:#"0"];
[endDate appendString:#":00 +0000"];
[startDate insertString:#":" atIndex:2];
[endDate insertString:#":" atIndex:2];
[startDate insertString:#"2013-06-08 " atIndex:0];
[endDate insertString:#"2013-06-08 " atIndex:0];
I realized that when adding events, I don't need to know the end time just the time interval. So i plan on taking the start TIME and comparing it to the end TIME and find the time interval that way.
I understand the DATE i give my string is of a constant date but that isn't the issue at the moment, I'll fix that later. But for now I would like to convert the NSString *startDate I created and stored the date/time string in to an NSDate *startDate so that I can use it as the start dat of an EKEvent.
Thank you guys.
Related
I am using this code for getting time zone
NSMutableArray *arrResult = [NSMutableArray new];
NSDateFormatter *dateFormatter = [NSDateFormatter new];
NSDate *myDate = [NSDate date];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
[dateFormatter setDateFormat:#"ZZZ"];
[[NSTimeZone knownTimeZoneNames] enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:obj];
[dateFormatter setTimeZone:timeZone];
NSString *dateString = [dateFormatter stringFromDate: myDate];
NSMutableString *mu = [NSMutableString stringWithString:dateString];
[mu insertString:#":" atIndex:3];
NSString *strResult = [NSString stringWithFormat:#"(GMT%#)%#",mu,obj];
[arrResult addObject:strResult];
}];
NSLog(#"%#", arrResult);
the response of this code is like this as what i want
"(GMT+01:00)Africa/Libreville",
"(GMT+00:00)Africa/Lome",
"(GMT+01:00)Africa/Luanda",
"(GMT+02:00)Africa/Lubumbashi",
"(GMT+02:00)Africa/Lusaka",
"(GMT+01:00)Africa/Malabo",
"(GMT+02:00)Africa/Maputo",
"(GMT+02:00)Africa/Maseru",
"(GMT+02:00)Africa/Mbabane",
"(GMT+03:00)Africa/Mogadishu",
"(GMT+00:00)Africa/Monrovia",
"(GMT+03:00)Africa/Nairobi",
"(GMT+01:00)Africa/Ndjamena",
"(GMT+01:00)Africa/Niamey",
"(GMT+00:00)Africa/Nouakchott",
"(GMT+00:00)Africa/Ouagadougou",
"(GMT+01:00)Africa/Porto-Novo",
"(GMT+00:00)Africa/Sao_Tome",
"(GMT+02:00)Africa/Tripoli",
"(GMT+01:00)Africa/Tunis",
i have to show this type in my label
but what i have to do is when we click on save only (Africa/Tripoli) this part in the database will be saved , i am not getting how to do this .
please help me
If you don't want (GMT+01:00) this bracket in list then you can make string like,
NSString *strResult = [NSString stringWithFormat:#"%#",obj];
[arrResult addObject:strResult];
So, that bracket part will not come.
If you want that bracket part and name both together also for different task then you can make another array called arrResult2 and make another string called strResult2 and do as i mentioned above.
So, you have two arrays. one(arrResult) have both that bracket and names and one(arrResult2) have names only.
If you want to separate string then,
NSString *str = #"(GMT+00:00)Africa/Lome";
NSString *newStr = [str substringFromIndex:11];
NSLog(#"new str : %#",newStr);
I found that every string have closing bracket at 11th index, so you can use it to get sub string from original one.
Hope this will help :)
I got the answer after many try if anyone want this then see here:-
NSString *zoneString = #"(GMT+13:00)Pacific/Tongatapu"
NSUInteger location = [zoneString rangeOfString:#")"].location+1;
NSLog(#"Trimed string:%#",[zoneString substringFromIndex:location]);
Trimed string:Pacific/Tongatapu
Lets say i have an array filled with several rows
dates = [NSArray arrayWithObjects:#"2012-05-01||Blue", #"2012-05-02||Red", #"2012-05-03||Green", #"2012-05-04||Orange", #"2012-05-05||Yellow", #"2012-05-06||Purple", #"2012-05-07||Silver", nil];
and then I have a date to search by 2012-05-01
How do i search for an object by only part of it without doing a big for( loop because this array will theoretically hold a few thousand cells.
EDIT:
if necessary how do i load the data into an NSDictionary? (i've never used them)
I know i can get the data like so
for(NSString *row in dates) {
NSString *date = [[row componentsSeperatedByString:#"||"] objectAtIndex:0];
NSString *color = [[row componentsSeperatedByString:#"||"] objectAtIndex:1];
}
NSMutableDictionary *colorsAndDates = [[NSMutableDictionary alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
for(NSString *row in dates) {
NSString *dateString = [[row componentsSeparatedByString:#"||"] objectAtIndex:0];
NSDate *date = [dateFormatter dateFromString:dateString];
NSString *color = [[row componentsSeparatedByString:#"||"] objectAtIndex:1];
[colorsAndDates setObject:color forKey:date];
}
If I am correct, this will format it into an NSDictionary, and then I can grab the color using:
NSString *dateToFind = #"2012-05-01";
NSDate *date = [dateFormatter dateFromString:dateToFind];
NSString *theColor = [colorsAndDates objectForKey:date];
Knowing this, I will have to go back and make it all revolve around NSDictionary instead of the strings they're in.
There's a couple of things you can do other than looping through the array:
1) Use a sorted array. Even if you need to keep the data in the initial order, you can make a sorted copy of it. Then you can do a binary search (if there are n items, check the n/2 item, if it's less than your date and repeat the process with only the data from n/2 to n, or if it's greater, then repeat with the data from 0 to n/2. Sort once, find many.
2) Create a dictionary on the fly using the data. You can use the the 10 character prefix of the data as the key. You'll have to maintain the dictionary along with the array, so this may not be practicable if you have a lot of changes. Create dictionary once, find many. (Note: despite the answers you've gotten, a dictionary may not be the best solution, particularly if you don't have unique keys (i.e. more than one record with the same date).
3) Forget the arrays and store your data in sqlite, and write a sql statement to get it. Most useful if you have a whole lot of data. You can use sqlite to build a primary key if you have duplicate dates in your data.
Creating a dictionary:
NSDictionary *dateDictionary = #{
#"2012-05-01" : #"Blue",
#"2012-05-02" : #"Red",
#"2012-05-03" : #"Green",
#"2012-05-04" : #"Orange",
#"2012-05-05" : #"Yellow",
#"2012-05-06" : #"Purple",
#"2012-05-07" : #"Silver"
};
NSString *date = #"2012-05-01";
NSString *dateColor = dateDictionary[date];
Using the example you gave (looping through the array to create a dictionary):
NSMutableDictionary *dateDictionary = [NSMutableDictionary dictionary];
for(NSString *row in dates) {
NSString *date = [[row componentsSeperatedByString:#"||"] objectAtIndex:0];
NSString *color = [[row componentsSeperatedByString:#"||"] objectAtIndex:1];
dateDictionary[date] = color;
}
NSString *date = #"2012-05-01";
NSString *dateColor = dateDictionary[date];
I'm learning how to develop for iPhone and i need to save de NSLog output on a local file on my machine to analyse the result in because I`ll run the application for a long time and I need to check after some hours running what was the output (and I want to save the output file on my machine from time to time, for example after every 30min).
How can I save the xcode output into a file?
Possibly not what you want, but I use this:
- (void)logIt:(NSString *)string {
// First send the string to NSLog
NSLog(#"%#", string);
// Setup date stuff
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-dd-MM"];
NSDate *date = [NSDate date];
// Paths - We're saving the data based on the day.
NSString *path = [NSString stringWithFormat:#"%#-logFile.txt", [formatter stringFromDate:date]];
NSString *writePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:path];
// We're going to want to append new data, so get the previous data.
NSString *fileContents = [NSString stringWithContentsOfFile:writePath encoding:NSUTF8StringEncoding error:nil];
// Write it to the string
string = [NSString stringWithFormat:#"%#\n%# - %#", fileContents, [formatter stringFromDate:date], string];
// Write to file stored at: "~/Library/Application\ Support/iPhone\ Simulator/*version*/Applications/*appGUID*/Documents/*date*-logFile.txt"
[string writeToFile:writePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
This writes the data into a file on your device (a daily file). If you want it to reset after each session you can surely modify the code to do that.
And of course you'll have to change all your existing NSLog() calls to use [self logIt:] instead.
This also works on a real device (but the file location is different of course).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
My question is: how do I load a specific image on a specific date and time in iOS?
I have searched the net but did not find anything useful.
I have a list of images in an imageArray and want every image to be shown on a specific date, time and order.
Fx. say I want to load MyImage on MyDateAndTime. How can I do this?
Image 1 - DateAndTime 1
Image 2 - DateAndTime 2
Image 3 - DateAndTime 3
Any suggestions is appreciated, please provide some source code if possible.
I put simple logic, edit it as per your requirement otherwise if you have any query related to my answer then please tells to me.
Best way is store your image with Name of dateTime (dd_MM_yyyy_HH_mm_ss) and access image name such like,
NSString *imageName
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd_MM_yyyy_HH_mm_ss"];
imageName = [NSString stringWithFormat:#"%#.png", [formatter stringFromDate:[NSDate date]]]; // here you can set specific dateTime, i putted current dateTime
Here you get imageName such like 19_10_2013_6_13_21.png
And by this image name you can get image from bundle or document directory.
If all you want is to show a different image every minute, use this, otherwise skip below to see helpful date information.
NSTimeInterval secondsInMinute = 60;
[NSTimer timerWithTimeInterval:secondsInMinute target:self selector:#selector(minuteChanged:) userInfo:nil repeats:YES];
- (void)minuteChanged:(id)sender {
// change image here
}
You question could have many different answers, do you want to create this date dynamically? or is it a a predefined date? One solution is to get get the timeInterval of the date you are looking for.
NSDate* rightNow = [NSDate date];
NSTimeInterval timeInterval = [rightNow timeIntervalSince1970];
// since time intervals are in seconds we can just append the
// date as easily as adding time
NSInteger secondsInMinute = 60;
NSInteger minutesInHour = 60;
NSInteger hoursInDay = 24;
NSInteger daysInWeek = 7;
NSInteger secondsInWeek = secondsInMinute * minutesInHour * hoursInDay * daysInWeek;
timeInterval = timeInterval + secondsInWeek;
NSDate* aWeekInFuture = [NSDate dateWithTimeIntervalSince1970:timeInterval];
that i would say is the easiest to under stand to set a date, but you could also use components to set a future date dynamically. This leads into some problems but here is how it's done.
NSDate* rightNow = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* dateCompenents = [calendar components:(NSDayCalendarUnit | NSWeekCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:rightNow];
[dateCompenents setDay:dateCompenents.day + 7];
NSDate* aWeekInFuture = [calendar dateFromComponents:dateCompenents];
to help explain this, here is some console logs
(lldb) po rightNow
$0 = 0x0b933440 2013-10-19 12:43:55 +0000
(lldb) po aWeekInFuture
$1 = 0x0ba32a60 2013-10-26 04:00:00 +0000
you see how the date is accurate for the day, year, month, but look at the exact time, the current time (right now) is 12:43:55 but the week in he future is 4:00:00 this is because i did not ask for the NSMinutesCalendarUnit, NSHoursCalendarUnit, NSSecondsCalendarUnit... so if i wanted a perfect date that would be inadequate unless i ask for every single thing, but you specifically may not need to be so accurate in fact you may even want to set your own time.
Now if you want a static date, a date the user enters, you will need to use NSDateFormatter example below
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setCalendar:currentCalendar];
[dateFormatter setDateFormat:#"mm/dd/yyyy"];
NSDate* birthdayDate = [dateFormatter dateFromString:#"10/05/2013"];
Now you wanted to know how would you know if today is the specified date that is saved. Lets say you stored the date in NSUserDefaults or on a server or some place, the easiest way to compare the dates is with the compare function of an NSDate
NSDate* rightNow = [NSDate date];
NSDate* storedDate = [[NSUserDefaults standardUserDefaults] objectForKey#"storedDate"] // some date from server, or UserDefaults
NSComparisonResult = [rightNow compare:storedDate];
this is a bit inadequate since it test for perfection but it will return values of NSOrderedSame if they are equal, NSOrderedDescending if storedDate is behind rightNow, and NSOrderedAscending if storedDate is in front of rightNow. This is all specific down to the time interval. If you just want a generic day, you will have to test it via components
NSDate* rightNow = [NSDate date];
NSDate* birthdayDate = [[NSUserDefaults standardUserDefaults] objectForKey#"birthday"]
NSDateComponents* todayComponents = [currentCalendar components:(NSDayCalendarUnit | NSMonthCalendarUnit) fromDate:rightNow];
NSDateComponents* birthdayComponents = [currentCalendar components:(NSDayCalendarUnit | NSMonthCalendarUnit) fromDate:birthdayDate];
BOOL dayIsTheSame = ( todayComponents.day == birthdayComponents.day );
BOOL monthIsTheSame = ( todayComponents.month == birthdayComponents.month );
BOOL todayIsBirthday = ( dayIsTheSame && monthIsTheSame );
if (todayIsBirthday) {
[self.imgViewBirthday setImage[UIImage imageNamed:#"cake.png"]];
}
In your question you specified an array of images, lets say you have a different image depending on which hour it is, or which minute, you would use the component, todayComponent.minute after asking for the NSMinutesCalendarUnit as the index of this array;
UIImage* currentImageToDisplay = [self.arrayOfImage objectAtIndex:todayComponent.minute];
self.imageView.image = currentImageToDisplay;
References:
NSDate,
NSDateFormatter,
NSDateComponents,
NSCalendar,
NSTimer
If I understood your problem now, one fancy approach using a recursive block you might check out is this:
#import <Foundation/Foundation.h>
#import <dispatch/dispatch.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSArray* dates = #[#1, #1, #1, #1, #1, #1, #1, #1, #1];
NSArray* urls = #[#"A", #"B", #"C", #"D", #"E", #"F", #"G", #"H", #"I"];
NSEnumerator* dateIter = [dates objectEnumerator];
NSEnumerator* urlIter = [urls objectEnumerator];
typedef void(^block_t)(NSEnumerator* dateIter, NSEnumerator* urlIter);
block_t asyncFunc;
__block __weak block_t _asyncFunc = asyncFunc = ^(NSEnumerator* dateIter, NSEnumerator* urlIter) {
NSNumber* date = [dateIter nextObject];
NSString* url = [urlIter nextObject];
if (date != nil && url != nil) {
double delayInSeconds = [date doubleValue];
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_global_queue(0, 0), ^(void){
NSLog(#"%#", url);
_asyncFunc(dateIter, urlIter);
});
}
else {
printf("\n");
return;
}
};
// start:
asyncFunc(dateIter, urlIter);
sleep (10);
}
return 0;
}
Note:
The "dates" are actually "delays" and the URLs are actually just strings in this example. You should be able to adjust this as you like. Of course, NSLog(#"%#", url); would actually display your image.
Also, the block asyncFunc is asynchronous!
I'm converting an NSString to an int for a project, in order to compare time stamps. This is the response I get from my NSLog when i convert it.
Server Time Stamp = 1363032033711 AND Server Time Stamp CONVERTED: 2147483647
I'm using this code to convert it:
NSString *msg = [NSString stringWithFormat:#"%#", message];
NSArray *subString = [msg componentsSeparatedByString:#" "];
NSString *timeStamp = [subString lastObject];
int serverTimeStamp = [timeStamp intValue];
NSLog(#"Server Time Stamp = %# AND Server Time Stamp CONVERTED: %d", timeStamp, serverTimeStamp);
I'm not sure why the converted number is so weird, is it a problem with my code, or with converting strings to ints?
1363032033711 is too big. It cannot be converted to an int (which appears to be 32 bits long on iOS). If you do a Google search for 2147483647, you find out that it's the maximal value of a 32-bit signed int. Perhaps that's how - [NSString intValue] indicates if it found a number that's too large to convert.
Solution: use a wider number type and NSScanner:
NSScanner *scn = [NSScanner scannerWithString:[subString lastObject]];
long long serverTimeStamp;
[scn scanLongLong:&serverTimeStamp];