How to add timestamp to my filePath? - iphone

I have a static file path to a download folder, files download fine but when I download a new one the old one gets replaced by new. I suppose because of static pathing. How do I add a timestamp to my code so whenever a new download is made the old one wouldn't get replaced?Or maybe even give download file the "original" filename from the actual array?
here is my download code:
-(void) Savefile {
[self.downloadfile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Wooopss!" message:#"Download failed. Try Again..." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else if (data) {
[data writeToFile:#"/Users/Danny/Desktop/PDFFile/hello.pdf" atomically:NO ];
NSLog(#"Downloading file...");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Downloading" message:#"File is being downloaded..." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}];
}

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"MMddYYYYmmss"];
NSString *filePath = [NSString stringWithFormat:#"/Users/Danny/Desktop/PDFFile/hello_%#.pdf", [dateFormatter stringFromDate:[NSDate date]]];
Which will give you this:
/Users/Danny/Desktop/PDFFile/hello_032620144401.pdf
Not entirely sure what you mean by:
Or maybe even give download file the "original" filename from the
actual array

Related

SWIFT: CDA to iOS 10 Health app

Is there any way to send a xml file (CDA) to health app from another application? Because my application is getting a xml file from a source and I want to send it directly to the new health app (iOS 10).
Create an HKCDADocumentSample and save it with an HKHealthStore.
First, check for authorization
(void) checkForAuthorization {
if ([HKHealthStore isHealthDataAvailable]) {
NSSet *setRead = [NSSet setWithObjects [HKObjectTypedocumentTypeForIdentifier:HKDocumentTypeIdentifierCDA], nil];
NSSet *setWrite = [NSSet setWithObjects:[HKObjectType documentTypeForIdentifier:HKDocumentTypeIdentifierCDA], nil];
[_store requestAuthorizationToShareTypes:setWrite readTypes:nil completion:^(BOOL success, NSError * _Nullable error) {
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
} else if (success) {
[self performSelectorOnMainThread:#selector(addDocumentToHealthApp) withObject:nil waitUntilDone:NO];
}
NSLog(#" Success = %#",success? #"YES" : #"NO");
} ];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Health Kit not supported in device." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
Second, add Record wmthod this will add a Health record to health app.
(void) addRecordToHealthApp
{
NSURL *cdaPath = [[NSBundle mainBundle] URLForResource:#"sample" withExtension:#"xml"];
NSString*stringPath = [cdaPath absoluteString];
NSData *dataOfCDAFile = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringPath]];
NSDate *now = [NSDate date];
int daysToAdd = 7;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
NSError *err;
HKCDADocumentSample *doc = [HKCDADocumentSample CDADocumentSampleWithData:dataOfCDAFile startDate:[NSDate date] endDate:newDate1 metadata:nil validationError:&err ];
UIAlertView *alert;
if (err) {
alert = [[UIAlertView alloc] initWithTitle:#"Error" message:err.localizedDescription delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
[_store saveObject:doc withCompletion:^(BOOL success, NSError * _Nullable error) {
NSLog("Stored %#",success?#"YES":#"NO");
}];
}

Downloading files from uiwebview in iphone sdk

Is there any way to download file from UIWebView i am using this code on my IBAction event
- (IBAction)saveFile:(id)sender {
// Get the URL of the loaded ressource
NSURL *theRessourcesURL = [[self.webDisplay request] URL];
NSString *fileExtension = [theRessourcesURL pathExtension];
if ([fileExtension isEqualToString:#"png"] || [fileExtension isEqualToString:#"jpg"] ||
[fileExtension isEqualToString:#"pdf"] || [fileExtension isEqualToString:#"html"]) {
// Get the filename of the loaded ressource form the UIWebView's request URL
NSString *filename = [theRessourcesURL lastPathComponent];
NSLog(#"Filename: %#", filename);
// Get the path to the App's Documents directory
NSString *docPath = [self documentsDirectoryPath];
// Combine the filename and the path to the documents dir into the full path
NSString *pathToDownloadTo = [NSString stringWithFormat:#"%#/%#", docPath, filename];
// Load the file from the remote server
NSData *tmp = [NSData dataWithContentsOfURL:theRessourcesURL];
// Save the loaded data if loaded successfully
if (tmp != nil) {
NSError *error = nil;
// Write the contents of our tmp object into a file
[tmp writeToFile:pathToDownloadTo options:NSDataWritingAtomic error:&error];
if (error != nil) {
NSLog(#"Failed to save the file: %#", [error description]);
} else {
// Display an UIAlertView that shows the users we saved the file :)
UIAlertView *filenameAlert = [[UIAlertView alloc] initWithTitle:#"File saved" message:[NSString stringWithFormat:#"The file %# has been saved.", filename] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[filenameAlert show];
[filenameAlert release];
}
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning"
message:#"File could not be loaded"
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alert show];
[alert release];
// File could notbe loaded -> handle errors
}
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning"
message:#"File type not supported"
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alert show];
[alert release];
// File type not supported
}
}
this code open the file in UIWebView , which i want to download and when i press the button the opened file get save.
But i want my UIWebView to behave like normal browser , when the download link appear in it and user press it, UIWebView show dialog with option open it or save it if user press save the file get save automatically and if user press open it file should open in UIWebView.
You can provide webView:shouldStartLoadWithRequest in your UIWebViewDelegate so that each time the user is about to move to another web page, you have the chance to check what the link looks like:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
if ([[[request URL] scheme] isEqual:#"http"] &&
[[[request URL] pathExtension]...])
<your download/save code here>
return NO; //-- no need to follow the link
}
return YES; //-- otherwise, follow the link
}

How to add events in iPhone using Event Kit framework

I am making a Restaurant application in which i need to add events in calendar, events information are coming from server, if client add any event it should show in calendar for that specified date, i have used event kit frame work and successfully added one event into the calendar, however how to add multiple events in calendar using event kit.
First of All, Add EventKit Framework and import it in .h file. Like below.
#import <EventKit/EventKit.h>
See Below Function and Modify it as per your need.
-(IBAction)AddEvent:(id)sender{
EKEventStore *eventSotre = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventSotre];
if([txtTitle.text isEqualToString:#""] || txtTitle.text == NULL)
txtTitle.text=#"Event Title";
event.title= txtTitle.text;
NSDate *duedate = pkrDate.date;
event.startDate =duedate;
event.endDate= [[NSDate alloc] initWithTimeInterval:600 sinceDate:duedate];
if(switchAlarm.on==TRUE){
NSArray *arrAlarm = [NSArray arrayWithObject:[EKAlarm alarmWithAbsoluteDate:duedate]];
event.alarms= arrAlarm;
}
[event setCalendar:[eventSotre defaultCalendarForNewEvents]];
NSError *err;
BOOL isSuceess=[eventSotre saveEvent:event span:EKSpanThisEvent error:&err];
if(isSuceess){
UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:#"Event" message:#"Event added in calendar" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertview show];
[alertview release];
}
else{
UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:#"Event" message:[err description] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertview show];
[alertview release];
}
[eventSotre release];
}
Please modify it as per your need. I just paste it from my one of app code.

Knowing when a file has uploaded to Dropbox

I have managed to get my app to upload to Dropbox like so:
NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
[self.restClient uploadFile:#"ZipTest.zip" toPath:[NSString stringWithFormat:#"/%#", self.dropboxFolderName] fromPath:docsPath];
But am now trying to verify it actually completed the upload. I know I can check for errors but how to check for completion?
I have tried using:`- (void)restClient:(DBRestClient*)client uploadProgress:(CGFloat)progress forFile:(NSString *)destPath from:(NSString *)srcPath {
Buut all I get is the number 1 printed even though I see on Dropbox the file has not completed the upload yet?
any ideas?
Thanks`
- (void)restClient:(DBRestClient *)client uploadedFile:(NSString *)srcPath {
NSString *filename = [[srcPath pathComponents]lastObject];
NSString *message = [NSString stringWithFormat:#"Uploaded File:%#",filename];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success"
message:message delegate:nil cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}
I used this code to check file is uploaded or not and after uploading this alert will show

memory problem with array releasing in objective-c

i am getting problem with this can any one help me
here is my code. This code work 1st click but when click 2 time it get error
malloc: error for object 0x4e226a4: incorrect checksum for freed object - object was probably modified after being freed.
** set a breakpoint in malloc_error_break to de**bug
- (void)updateTextViewContents {
content = [[NSMutableString alloc] init];
for (int i = 0; i <[ _scoresArray count]; i++)
{
NSMutableString *data = [_scoresArray objectAtIndex:i];
[content appendString:data];
if([content isEqualToString:UserText.text]&&[content isEqualToString:PassText.text])
{
UIAlertView *alt = [[UIAlertView alloc] initWithTitle:nil message:#"Valid User" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alt show];
[alt release];
[content release];
}
else
{
UIAlertView *alt1 = [[UIAlertView alloc] initWithTitle:nil message:#"NOT A Valid User" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alt1 show];
[alt1 release];
}
}
when i release over here it work but when i click 2nd time by entering right user name and password both alter view display at time .I think it will happen because of array get add at every cilck that's why both alter view dispaly at time how i sovle this .
//[content release];
}
Here generate memory problem because of,
you release content NSMutableString in if condition and then append it again.
So, Don't release in to for loop, release it out of for loop.
- (void)updateTextViewContents
{
content = [[NSMutableString alloc] init];
for (int i = 0; i <[ _scoresArray count]; i++)
{
NSMutableString *data = [_scoresArray objectAtIndex:i];
[content appendString:data];
if([content isEqualToString:UserText.text]&&[content isEqualToString:PassText.text])
{
UIAlertView *alt = [[UIAlertView alloc] initWithTitle:nil message:#"Valid User" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alt show];
[alt release];
//[content release]; - Not release here.
}
else
{
UIAlertView *alt1 = [[UIAlertView alloc] initWithTitle:nil message:#"NOT A Valid User" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alt1 show];
[alt1 release];
}
}
[content release];
Can't you replace
NSMutableString *data = [_scoresArray objectAtIndex:i];
[content appendString:data];
with this
[content appendString:[_scoresArray objectAtIndex:i]];
your both alert is showing because of your loop put break after it is valid user because you must not go through loop after it is valid user
hope this will help
good luck
You have release content in the if condition. For the next iteration you are again trying to append data to content, which is already released if the condition was true in previous iteration. And thus you are getting that error object was probably modified after being freed.