I'm new to IOS development and i have a problem in downloading my attachments from mail.when i'm trying to download image or PDF attachments from my mail to documents directory using MailCore2 SDK it is downloading sucessfully.but my problem is that the downloaded image or PDF displays nothing (i.e.,).It gives me the file but with a empty file with zero bytes.im able to know that problem is with the NSData what im using to writeToFile is incorrect.But im unable to solve it.please help me.
Here is the code i'm using to download file from mail
MCOIMAPFetchContentOperation * op = [self.imapSession fetchMessageByUIDOperationWithFolder:#"INBOX" uid:[sender tag]];
[op start:^(NSError * error, NSData * data) {
if ([error code] != MCOErrorNone) {
return;
}
NSAssert(data != nil, #"data != nil");
MCOMessageParser * msg = [MCOMessageParser messageParserWithData:data];
if ([msg.attachments count] > 0)
{
MCOIMAPPart *part = [msg.attachments objectAtIndex:0];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *saveDirectory = [paths objectAtIndex:0];
NSLog(#"%#",part.filename);
NSString *attachmentPath = [[saveDirectory stringByAppendingString:#"/Downloads"] stringByAppendingPathComponent:part.filename];
if (fileExists) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message"
message:#"Fail Existed in Download Path."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
else{
[msg.data writeToFile:attachmentPath atomically:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message"
message:#"Download Success /n Saved in Downloads"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
[self.tableView reloadData];
}
}];
please help me to get out of this problem and tell me where am i doing mistake.
Thanks in advance.
I used like this:
MCOIMAPFetchContentOperation * op = [self.imapSession fetchMessageByUIDOperationWithFolder:#"INBOX" uid:[sender tag]];
[op start:^(NSError * error, NSData * data)
{
if ([error code] != MCOErrorNone)
{
return;
}
NSAssert(data != nil, #"data != nil");
MCOMessageParser * msg = [MCOMessageParser messageParserWithData:data];
if ([msg.attachments count] > 0)
{
MCOAttachment *attachment = [msg.attachments objectAtIndex:0];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *saveDirectory = [paths objectAtIndex:0];
NSLog(#"%#",attachment.filename);
NSString *downLoadDirectory = [saveDirectory stringByAppendingString:#"/Downloads"];
if (![[NSFileManager defaultManager] fileExistsAtPath:downLoadDirectory])
{
[[NSFileManager defaultManager] createDirectoryAtPath:downLoadDirectory withIntermediateDirectories:YES attributes:nil error:nil];
}
NSString *attachmentPath = [downLoadDirectory stringByAppendingPathComponent:attachment.filename];
if ([[NSFileManager defaultManager] fileExistsAtPath:attachmentPath])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message"
message:#"Fail Existed in Download Path."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
else
{
BOOL res = [[attachment data] writeToFile:attachmentPath atomically:YES];
if (res)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message"
message:#"Download Success /n Saved in Downloads"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
}
}];
I hope they are useful.
Related
i am downloading a pdf file from server,and i can see the file in my simulator.But i can't find in my device. I am saving the file into the document file. Below is my code,am sure my code is perfect,
-(void)downloadPdfBtnPressed:(id)sender
{
NSString *dowloadURL = [DownloadUrlArray objectAtIndex:[sender tag ]];
NSString *filename =[dowloadURL lastPathComponent];
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"/PDFDownload"];
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:nil];
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:dowloadURL]];
if(pdfData)
{
stringPath = [stringPath stringByAppendingPathComponent:filename];
[pdfData writeToFile:stringPath atomically:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"PDF"
message:#"PDF file is downloaded"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
I have a NSDictionary in a project that was created over time and i need to take all the data from it from this project into another project.
Any idea how can i achive it without adding it one by one?
I thought about extracting everything into arrays and to pass arrays but its not really a good option
Probaly not the best solution but it will work fine.
You can convert the dictionary in to a string using the following steps.
Then you log the string and copy it. After that you can do a reverse of these steps in your new project.
Project 1
NSDictionary *dictionary = [NSDictionary alloc]init];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error];
NSString *dictionaryString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#",dictionaryString); #Copy this string from the debugger
Project 2
NSError *error;
NSString *dictionaryString = #"PASTE_DEBUGGER_STRING";
NSData *jsonData = [dictionaryString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
I would write it to a file and then import it in your new app. First you would ran the method in your app, and then take the file from the documents folder in iTunes. Add it to the documents folder in your new app and add the reading code.
To save it:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *stringsPlistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myDictionary.plist"];
BOOL success = [myDictionary writeToFile:stringsPlistPath atomically:YES];
if (success) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Your configuration file is in the Documents folder of the app which is accessible via iTunes." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"There was a problem creating the configuration file. Please try again." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
To read it:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *stringsPlistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myDictionary.plist"];
NSDictionary *loadedDictionary = [NSDictionary dictionaryWithContentsOfFile:stringsPlistPath];
This will leave your file there. If you wanted to delete it:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
BOOL success = [fileManager removeItemAtPath:stringsPlistPath error:&error];
if (success) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"The configuration file was successfully loaded and has now been removed." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"The configuration file was successfully loaded but could not be removed. You will need to remove it manually." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
I have a requirement of downloading .zip file from server and use it to project after extracting it. I have successfully downloaded the .sqlite file and i am able to extract it using right click(manually) but when i am trying to extract it using minizip and SSZipArchive or ZipArchive it's giving an error "Can't open the file".
If i extract .sqlite manually and compress .sqlite file by right clicking in mac then my code is extracting it completely but whenever i try to extract downloaded file directly then this issue is occurring.
I have applied below name formats for writing and extracting file.
While writing file the name was XYZ.sqlite.zip but it is also giving error
XYZ.zip and contained file name is XYZ.sqlite. This also giving error
I also have written file with name XYZ.sqlite.zip and then rename it with XYZ.zip and then extracted but that was also not working.
Below is the code.
For Downloading the file:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:zipURL]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[zipURL lastPathComponent]];
operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:path shouldResume:YES];
[operation.securityPolicy setAllowInvalidCertificates:YES];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
[self unzipDBFile:path];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation setProgressiveDownloadProgressBlock:
^(AFDownloadRequestOperation *operation, NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
NSArray *progress = [NSArray arrayWithObjects:obj_Pro,[NSNumber numberWithFloat:totalBytesReadForFile/(float)totalBytesExpectedToReadForFile], nil];
[self performSelectorOnMainThread:#selector(updateProgressBar:) withObject:progress waitUntilDone:NO];
}];
[operation start];
For Extracting the file:
-(void)unzipDBFile:(NSString *)filePath
{
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSString *outputPath = [documentDir stringByAppendingPathComponent:#"/DBFolder"];
BOOL isExtracted =[SSZipArchive unzipFileAtPath:outputPath toDestination:documentDir];
// NSString *filepath = [[NSBundle mainBundle] pathForResource:#"ZipFileName" ofType:#"zip"];
// ZipArchive *zipArchive = [[ZipArchive alloc] init];
// [zipArchive UnzipOpenFile:filePath];
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *path = [paths objectAtIndex:0];
// BOOL isExtracted=[zipArchive UnzipFileTo:path overWrite:YES];
// NSLog(#"PATH=%#",path);
if (!isExtracted)
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Error in extracting" message:#"" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}else{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Extract Success" message:#"" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
// [zipArchive UnzipCloseFile];
// [zipArchive release];
}
Below is the code for update progressbar:
- (void)updateProgressBar:(NSArray *)progress
{
UIProgressView *pgr = (UIProgressView *)[progress objectAtIndex:0];
[pgr setProgress:[[progress objectAtIndex:1] floatValue]];
}
I have examined the issue and found that .net developer, Who created .zip has used gzip compression so minizip is not able to extract it.
For decompress it, I have used iOS zlib framework and below code and that has solved my problem. You have to add below two things in the header before implementing this method.
#import <zlib.h>
#define CHUNK 16384
-(BOOL)unzipDBFile:(NSString *)filePath
{
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
documentDir=[documentDir stringByAppendingPathComponent:DATABASE_FILE_NAME];
gzFile file = gzopen([filePath UTF8String], "rb");
FILE *dest = fopen([documentDir UTF8String], "w");
unsigned char buffer[CHUNK];
int uncompressedLength;
while ((uncompressedLength = gzread(file, buffer, CHUNK)) ) {
// got data out of our file
if(fwrite(buffer, 1, uncompressedLength, dest) != uncompressedLength || ferror(dest)) {
return FALSE;
}
}
fclose(dest);
gzclose(file);
return TRUE;
}
I am trying to delete a video from the document directory, but the video isn't deleting.
Here is how I am trying to delete the video:
//Delete Video
NSError *error = nil;
//NSData *videoData = [NSData dataWithContentsOfURL:self.finalURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *tempPath = [documentsDirectory stringByAppendingFormat:#"/vid1.mp4"];
[[NSFileManager defaultManager] removeItemAtPath: tempPath error: &error];
UIAlertView *removeSuccessFulAlert=[[UIAlertView alloc]initWithTitle:#"Congratulation:" message:#"Successfully removed" delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[removeSuccessFulAlert show];
You might get a good hint at your problem if you put in a line after your "removeItemAtPath" that says something like:
BOOL success = [[NSFileManager defaultManager] removeItemAtPath: tempPath error: &error];
if(!success)
{
NSLog(#"error from removing item at path %# is %#",
tempPath, [error localizedDescription]);
} else {
UIAlertView *removeSuccessFulAlert=[[UIAlertView alloc]initWithTitle:#"Congratulation:" message:#"Successfully removed" delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[removeSuccessFulAlert show];
}
Try this instead:
NSString *tempPath = [documentsDirectory stringByAppendingPathComponent:#"vid1.mp4"];
I use the following code, but it only checks first column in first row. But I want to check first column of all rows in a csv file. Please help
- (void) SearchStudent
{
NSArray *DocumentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //I upload the csv file to documents folder of the app through itunes
NSString *DocumentDirectory = [DocumentPath objectAtIndex:0];
NSString *FullPath = [DocumentDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"example.csv"]];
NSString * pstrCSVFile= [NSString stringWithContentsOfFile:FullPath encoding:NSASCIIStringEncoding error:NULL];
NSArray * paRowsOfCSVFile= [pstrCSVFile componentsSeparatedByString:#"\n"];
NSArray *paColumnsOfRow;
NSString *pstrFirstColumn;
for(NSString * pstrRow in paRowsOfCSVFile)
{
paColumnsOfRow= [pstrRow componentsSeparatedByString:#","];
pstrFirstColumn= [paColumnsOfRow objectAtIndex:0];
if([pstrFirstColumn localizedCaseInsensitiveCompare:GWIDText.text] == NSOrderedSame)
{
UIAlertView *alertingFileName = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Found" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertingFileName show];
break;
}
else
{
UIAlertView *alertingFileName1 = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Not Found" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertingFileName1 show];
}
}
}
paColumnsOfRow contain all rows.