iphone: copy or move file from document directory folder - iphone

Here is my code.
NSArray *pathSong = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *toPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"Songs"];
NSString *fromPath=[[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"abc"];
NSString *strdestination = [fromPath stringByAppendingPathComponent:#"sg.mp3"];
NSError *Error;
if([[NSFileManager defaultManager]fileExistsAtPath:strdestination]){
if([[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error]==NO){
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"copy" message:[NSString stringWithFormat:#"%#",Error] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[Alert show];
}
else{
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"Not copy" message:[NSString stringWithFormat:#"%#",Error] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[Alert show];
}
}
I am getting the error logo :
Error Domain=NSCocoaErrorDominCode=516 "The operation couldn't be
completed .(Cocoa arrow 516.)" userInfo=0x681abf0
NSUnderlyingError =0x681b920 "The operation couldn't be completed
.File exists"
abc folder there is no song name "sg.mp3" but I'm still getting the file exists error. I don't know where I did mistake?

There is two issues in your code:
You need to remove the file if it is already there
You need to specify a name for the destination file, means if you use like:
NSString *toPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"Songs"];
and
[[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error];
Then if copy occurs, it will copy the Sg.mp3 file as Songs without any type.
So you need to write it like:
NSArray *pathSong = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *tempPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"Songs"];
NSString *toPath = [tempPath stringByAppendingPathComponent:#"yourFileName.mp3"];
NSString *fromPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"abc"];
NSString *strdestination = [fromPath stringByAppendingPathComponent:#"sg.mp3"];
NSError *Error = nil;
if([[NSFileManager defaultManager]fileExistsAtPath:strdestination])
{
if([[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error]==NO)
{
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"copy" message:[NSString stringWithFormat:#"%#",Error] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[Alert show];
}
else
{
[fileManager removeItemAtPath:strdestination error:NULL];
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"Not copy" message:[NSString stringWithFormat:#"%#",Error] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[Alert show];
}
}
This code will remove the file if exist at destination and then copy the sg.mp3 from abc folder to Songs folder with the name yourFileName.mp3

Drawing upon the Midhun MP answer, here's a helper
BOOL moveFile(NSString *srcPath, NSString *dstPath)
{
NSLog(#"moving %# -> %#", srcPath, dstPath);
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:dstPath])
{
// in my usecase this is a hard error, bolt to prevent overwriting
return NO;
}
if ([fm fileExistsAtPath:srcPath])
{
NSError *error = nil;
NSString *destDir = [dstPath stringByDeletingLastPathComponent];
[fm createDirectoryAtPath:destDir withIntermediateDirectories:YES attributes:nil error:nil];
if ([[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dstPath error:&error]==NO)
{
NSLog(#"failure declassing %#", srcPath);
return NO;
}
else
{
[fm removeItemAtPath:srcPath error:NULL]; // gr8t success
return YES;
}
}
return NO;
}

I think its because you are trying to overwrite a file with your copy.
Check your permission mask, try using the cache instead of the documents directory.
Do you mean if(!fileExistsAtPath)

You need to delete the file that's already there:
NSArray *pathSong = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *toPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"Songs"];
NSString *fromPath=[[pathSong objectAtIndex:0] stringByAppendingPathComponent:#"abc"];
NSString *strdestination = [fromPath stringByAppendingPathComponent:#"sg.mp3"];
NSError *Error;
//DELETE THE FILE AT THE LOCATION YOU'RE COPYING TO
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:strdestination error:NULL];
if([[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error]==NO){
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"copy" message:[NSString stringWithFormat:#"%#",Error] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[Alert show];
}
else{
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"Not copy" message:[NSString stringWithFormat:#"%#",Error] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[Alert show];
}

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");
}];
}

NSString variable is not NSstring

I have a problem with NSString variable.
.h file
NSString *strDeleteFilePath;
#property (nonatomic,retain) NSString* strDeleteFilePath;
.m File
#synthesize strDeleteFilePath;
//After that when delete button click
-(IBAction)deleteButton:(id)sender {
UIButton *bt=(UIButton *)sender;
strDeleteFilePath=[FunctionManager getDocumentDirectoryPath:#"MyPhotos"];
strDeleteFilePath=[NSString stringWithFormat:#"%#/%#",strDeleteFilePath,[arrSaveImage objectAtIndex:bt.tag]];
NSLog(#"strDeletePath=%#",strDeleteFilePath);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Are you sure you want to delete this photo" delegate:self cancelButtonTitle:#"Delete" otherButtonTitles:#"Cancel", nil];
[alert show];
[alert release];
}
nslog prints proper path in string as below :
strDeletePath=/Users/Samir/Library/Application Support/iPhone
Simulator/6.0/Applications/A72B7488-ABCB-48EC-91D0-CEE87FA121FE/Documents/MyPhotos/Dt20130411164806.png
when click on delete button in alert view...
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0){
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if(![fileManager removeItemAtPath:strDeleteFilePath error:&error]) {
NSLog(#"Delete failed:%#", error);
} else {
NSLog(#"image removed: %#", strDeleteFilePath);
}
[self setScrollviewItem];
}
}
it crash on line if(![fileManager removeItemAtPath:strDeleteFilePath error:&error]) and give following error ExE_BAD..ACCESS...
Thank You, in Advance.
Use self. strDeleteFilePath instead of strDeleteFilePath.
Try this
-(IBAction)deleteButton:(id)sender {
UIButton *bt=(UIButton *)sender;
strDeleteFilePath=[FunctionManager getDocumentDirectoryPath:#"MyPhotos"];
strDeleteFilePath=[[NSString alloc] initWithFormat:#"%#/%#",strDeleteFilePath,[arrSaveImage objectAtIndex:bt.tag]]; //change is here
NSLog(#"strDeletePath=%#",strDeleteFilePath);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Are you sure you want to delete this photo" delegate:self cancelButtonTitle:#"Delete" otherButtonTitles:#"Cancel", nil];
[alert show];
[alert release];
}
replace this :
if(![fileManager removeItemAtPath:strDeleteFilePath error:&error]) {
NSLog(#"Delete failed:%#", error);
} else {
NSLog(#"image removed: %#", strDeleteFilePath);
}
with:
if([fileManager fileExistsAtPath: strDeleteFilePath])
{
[fileManager removeItemAtPath: strDeleteFilePath error: nil];
}
else{
NSLog(#"File not found");
}

How to zip file

I want to zip file in my application. Can anybody tell me the code exactly.
I have used this code to unzip file:
I used: ZipArchive.h
self.fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"document directory path:%#",paths);
self.documentDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/abc", self.documentDirectory];
NSLog(#"file path is:%#",filePath);
NSString *fileContent = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"data.zip"];
NSData *unzipData = [NSData dataWithContentsOfFile:fileContent];
[self.fileManager createFileAtPath:filePath contents:unzipData attributes:nil];
// here we go, unzipping code
ZipArchive *zipArchive = [[ZipArchive alloc] init];
if ([zipArchive UnzipOpenFile:filePath])
{
if ([zipArchive UnzipFileTo:self.documentDirectory overWrite:NO])
{
NSLog(#"Archive unzip success");
[self.fileManager removeItemAtPath:filePath error:NULL];
}
else
{
NSLog(#"Failure to unzip archive");
}
}
else
{
NSLog(#"Failure to open archive");
}
[zipArchive release];
I use SSZipArchive
NSError* error = nil;
BOOL ok = [SSZipArchive unzipFileAtPath:source_path toDestination:dest_path overwrite:YES password:nil error:&error];
DLog(#"unzip status: %i %#", (int)ok, error);
if(ok) {
[self performSelectorOnMainThread:#selector(unzipCompleted) withObject:nil waitUntilDone:NO];
} else {
[self performSelectorOnMainThread:#selector(unzipFailed:) withObject:error waitUntilDone:YES];
}
You can create zip file using zipArchive. ZipArchive Download the source code and add into your application folder.
Then in your header file add: #import "ZipArchive/ZipArchive.h"
To create a zip file is simple, just use the following code:
BOOL ret = [zip CreateZipFile2:l_zipfile];
ret = [zip addFileToZip:l_photo newname:objectForZip];
if( ![zip CloseZipFile2] )
{
}
[zip release];
you will get your answer is here . a c based library you will get by which you can zip and unzip your files programmatically
.http://stackoverflow.com/questions/1546541/how-can-we-unzip-a-file-in-objective-c
This code will work perfectly to zip a file.
ZipArchive *zip = [[ZipArchive alloc] init];
if(![zip UnzipOpenFile:fileToZipPath]) {
//open file is there
if ([zip CreateZipFile2:newZipFilePath overWrite:YES]) {
//zipped successfully
NSLog(#"Archive zip Success");
}
} else {
NSLog(#"Failure To Zip Archive");
}
}
I have used this to zip my documents folder.
You can separate out the part where you want to zip a file.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
BOOL isDir = NO;
NSArray *subpaths;
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:docDirectory isDirectory:&isDir] && isDir)
{
subpaths = [fileManager subpathsAtPath:docDirectory];
}
NSString *archivePath = [docDirectory stringByAppendingString:#"/doc.zip"];
ZipArchive *archiver = [[ZipArchive alloc] init];
[archiver CreateZipFile2:archivePath];
for(NSString *path in subpaths)
{
NSString *longPath = [docDirectory stringByAppendingPathComponent:path];
if([fileManager fileExistsAtPath:longPath isDirectory:&isDir] && !isDir)
{
[archiver addFileToZip:longPath newname:path];
}
}
BOOL successCompressing = [archiver CloseZipFile2];
if(successCompressing)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Success"
message:#"Zipping Successful!!!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Cannot zip Docs Folder"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
[archiver release];

Sending Email in background in iphone sdk with body

I am developing on app in that i want to send email at the back ground.
for that i used the "SKPSMTP" library but when i got the mail it is without body so can any one tell me where i m wrong in my code.
following is the code on button click..
- (void)sendMessageInBack:(id)anObject
{
if(![self validateEmail:txt_email.text])
{
if([txt_email.text isEqualToString:#""] )
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Mandatory field" message:#"Please fill complete email" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
if(self.interfaceOrientation==UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation==UIInterfaceOrientationLandscapeRight )
{
if(rotate)
[btn_Send setImage:[UIImage imageNamed:#"send_button.png"] forState:UIControlStateNormal];
}
else if(self.interfaceOrientation==UIInterfaceOrientationPortrait || self.interfaceOrientation==UIInterfaceOrientationPortraitUpsideDown )
{
if(rotate)
[btn_Send setImage:[UIImage imageNamed:#"send button1.png"] forState:UIControlStateNormal];
}
NSLog(#"Start Sending");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"RequestReview.txt"];
NSData *dataObj = [NSData dataWithContentsOfFile:writableDBPath];
//NSString *mailid;
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail =#"spymekdemo#gmail.com";
testMsg.toEmail = #"priyanka.chinchmalatpure#gmail.com";// txtEmail.text;
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = #"spymekdemo#gmail.com";
testMsg.pass =#"spymek123";
testMsg.subject =#"Sbject"; //[NSString stringWithFormat:#"Reply to Review From %#", txtName.text];
testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!
// Only do this for self-signed certs!
testMsg.validateSSLChain = NO;
testMsg.delegate = self;
NSString *deviceIdentifier=[NSString stringWithFormat:#"%#",[[UIDevice currentDevice]uniqueIdentifier]];//[NSString stringWithFormat:#"%#",deviceToken.uniqueIdentifier];
NSLog(#"%#",deviceIdentifier);
//NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
// [NSString stringWithFormat:#"Request Review\n\nDevice Identifier=%#\nProduct Name=%#\nProduct Download URL=%#\nUser Name=%#\nEmail=%#\nPromo Code=%#\nDescription Of Product=%#\n\n\n", deviceIdentifier, txtProduct.text,txtDownloadURL.text, txtName.text,txtEmail.text,txtPromocode.text, txtDescription.text]
// ,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/html",kSKPSMTPPartContentTypeKey,
[NSString stringWithFormat:#"<h2>Request Review</h2><br/><br/><b>Thank you for giving us your review</b> <br/>Device Identifier=%#<br/>Product Name=<br/>Product Download URL=<br/>User Name=<br/>Email=<br/>Promo Code=<br/>Description Of Product=<br/><br/><br/>", deviceIdentifier]
,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
// [NSString stringWithFormat:#"<h3>Review App</h3> <br/> <br/><b>Name=%#<b><br/> <br/>,\n<u>Email=%#</u><br/> <br/>,\nPassword=%#,<br/><br/> <b>\nComments=%#\n\n</b><br/>",txtName.text,txtMailId.text, txtPassword.text, txtComment.text],kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
// #"<html><body><h1>Review App</h1> <br/> <b>Some text to include in body</b></body></html>"
NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:#"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"%#.txt\"",txt_name.text],kSKPSMTPPartContentTypeKey,
[NSString stringWithFormat:#"attachment;\r\n\tfilename=\"%#.txt\"",txt_name.text],kSKPSMTPPartContentDispositionKey,[dataObj encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,vcfPart, nil]; //vcfPart
[testMsg send];
}
}
rotate=YES;
}
- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
[message release];
//open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Unable to send email"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
//[self ClearFile];
//UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Request Review" message:#"Review Posting failed.. Try Again Later.." delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Done",nil];
}
- (void)messageSent:(SKPSMTPMessage *)message
{
[message release];
NSLog(#"delegate - message sent");
}

iPhone: How to Write an Image to Disk in the App Directories

I am working on an iPhone project in which I need save camera images to disk and file but the code below fails:
(************
-(void)imagePickerController:(UIImagePickerController *) picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
imageView.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
imgglobal =imageView.image;
NSString *newFilePath = [NSHomeDirectory() stringByAppendingPathComponent: #"~/Users/abc/Library/Application Support/iPhone Simulator/User/Applications/SAVE_IMAGE_TEST1.JPG"];
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 1.0);
NSData *data = imageData;
if (imageData != nil) {
[imageData writeToFile:newFilePath atomically:YES];
}
if ([[NSFileManager defaultManager] createFileAtPath:#"~/Users/abc/Library/Application Support/iPhone Simulator/User/Applications/SAVE_IMAGE_TEST1.JPG" contents:data attributes:nil])
{
UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:#"Success" message:#"Image was successfully saved to the Photo Library." delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[successAlert show];
[successAlert release];
} else {
UIAlertView *failureAlert = [[UIAlertView alloc] initWithTitle:#"Failure" message:#"Failed to save image to the Photo Library." delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[failureAlert show];
[failureAlert release];
}
}
You shouldn't have a hard coded path to the simulator directories. That will fail on the device or when the simulator resets. Neither should you save user data anywhere but the app's Document folder.
Instead use:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathToDocuments=[paths objectAtIndex:0];
This will return the current path the app's Document directory regardless of where it is run or what has changed.
You should never use absolute paths in iPhone code because the system scrambles the paths for security. Always use the functions that dynamically retrieve the paths as needed.