NSData getting trucated while converting from Pdf - ios

I am trying to upload a pdf from iClouds in iPhone in Objective C. The following is my code which gets triggered on click.
UIDocumentPickerViewController *doc = [[UIDocumentPickerViewController alloc]initWithDocumentTypes:#[#"public.composite-content"] inMode:UIDocumentPickerModeImport];
doc.delegate = (id)self;
doc.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:doc animated:YES completion:nil];//getting the path of the file selected through didPickDocumentAtURL
NSString *path = [url path];//converting in to data in two different ways but getting truncated nsdata
NSData *data3 = [[NSFileManager defaultManager] contentsAtPath:path];//Truncating
NSData *data1 = [NSData dataWithContentsOfFile:path];//Truncating Both data3 and data1 are getting truncated after 32767 characters.
Questions:
Is this correct format for importing a .pdf into NSData?
Is there any limit for NSData? (I am asking this because it's getting truncated exactly after 32767 characters)

I solved it by calling the delegate method of UIDocumentPickerViewController
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url{
if (controller.documentPickerMode== UIDocumentPickerModeImport) {
//taking the path of the file selected
NSString *path = [url path];
//converting to NSData
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
//converting to base64 string
base64String = [data base64EncodedStringWithOptions:kNilOptions];
}
}

Related

ios sending docx attachments with mfMailComposer fails

I am trying to attach a docx file when sending email but I am having trouble. These 2 lines are always nil. The variables filename and extension are not nil but file comes up as nil. Not sure if this matters but the docx file is dynamically generated, what if I were to use the NSData from the generated file instead of creating a new NSData variable here?
filepath = /Users/myself/components/file.docx
NSString *file = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
NSData *fileData
= [NSData dataWithContentsOfFile:file];
here is the code
-(void)sendEmail:(NSString*)filePath{
if ([MFMailComposeViewController canSendMail])
{
mailComposer = [[MFMailComposeViewController alloc]init];
mailComposer.mailComposeDelegate = self;
[mailComposer setToRecipients:#[#"name#gmail.com"]];
[mailComposer setSubject:#"Mobile File Attachment"];
[mailComposer setMessageBody:#"DocX file attached" isHTML:NO];
// Determine the file name and extension
if(![filePath isEqual:nil])
{
NSArray *filepart = [filePath componentsSeparatedByString:#"."];
NSString *filename = [filepart objectAtIndex:0];
NSString *extension = [filepart objectAtIndex:1];
// Get the resource path and read the file using NSData
NSString *file = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
NSData *fileData = [NSData dataWithContentsOfFile:file];
// Determine the MIME type
NSString *mimeType;
if ([extension isEqualToString:#"jpg"]) {
mimeType = #"image/jpeg";
} else if ([extension isEqualToString:#"png"]) {
mimeType = #"image/png";
} else if ([extension isEqualToString:#"doc"]) {
mimeType = #"application/msword";
} else if ([extension isEqualToString:#"docx"]) {
mimeType = #"application/msword";
} else if ([extension isEqualToString:#"ppt"]) {
mimeType = #"application/vnd.ms-powerpoint";
} else if ([extension isEqualToString:#"html"]) {
mimeType = #"text/html";
} else if ([extension isEqualToString:#"pdf"]) {
mimeType = #"application/pdf";
}
// Add attachment
[mailComposer addAttachmentData:fileData mimeType:mimeType fileName:filename];
}
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:mailComposer animated:YES completion:nil];
}
EDIT: add value of filePath and this is how I generate the file
NSAttributedString *str = [[NSAttributedString alloc] initWithAttributedString:_textV.attributedText];
//convert to html then write to a .docx file to export to docx
NSData *data = [str dataFromRange:(NSRange){0, [str length]} documentAttributes:#{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} error:NULL];
[data writeToFile:#"/Users/myself/components/file.docx" atomically:YES];
The issue here as you've mentioned is those two lines - if the file is dynamically generated, it won't be in the main bundle - that's the bundle of an application (each app on OS X and iOS is a folder /"bundle" or "package"/, which contains other files. Using this method, you are retrieving files that are packaged with the app.
If you are generating the content, you are likely writing it to a different path (temp directory?) - hence the pathForResource: method returns nil (the resource is not found within the app bundle), and NSData initializer fails when the path is nil -> returns nil as well.
You most likely want this: NSData *fileData = [NSData dataWithContentsOfFile:filePath];.
Few notes:
do not use isEqual:nil. Simply use filePath != nil (it's easier to read and it's faster on execution).
NSString has a pathExtension property, which will retrieve the property for you.
using file paths is unofficially deprecated in favor of using URLs: NSURL *fileURL = [NSURL fileURLWithPath:filePath]; You should use URLs in new code.
Please, post a sample value of filePath if this doesn't help.

How to get url from video reference url

I have a url of video from photo library :-
/var/mobile/Applications/9BC2EBC4-7A71-4C8B-8BFB-D25D01E4CA83/Documents/IMG_5244.MOV
How can i get convert it to NSData I am tried following but nothing worked:
NSString* fileName = movieAsset.defaultRepresentation.filename;
NSURL* fileUrl = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject]URLByAppendingPathComponent:fileName];
NSString *str = [fileUrl path];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
[arrVideoUrls addObject:fileUrl];
Here in your code you have add NSString as an URL and try to convert that NSString URL to NSData, so here first convert that string url to NSURL and then convert it in to NSData like below...
NSString *strVideoURL = #"assets-library://asset/asset.MOV?id=2EBD925F-D275-403E-A6A4-3487134D9B9D&ext=MOV";
NSURL *urlVideo = [NSURL URLWithString:strVideoURL];
NSData *videoData = [NSData dataWithContentsOfURL:urlvideo]];

iOS8: UIDocumentPickerViewController get NSData

I have implement UIDocumentPickerViewController according docs and now trying to get NSData from picked file in delegate method, but [[NSData alloc] initWithContentsOfURL:] returns nil:
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url{
NSData* documentData = [[NSData alloc] initWithContentsOfURL:url];
//documentData is nil
documentData = [[NSData alloc] initWithContentsOfFile:[url path]];
//documentData is still nil :(
}
I'm using Xcode6 beta6, iPhone simulator, document picker mode is UIDocumentPickerModeImport.
Trying to retrieve documents saved to iCloude Drive.
Elaborating on #cescofry's answer a bit here regarding iWork files (.pages, .numbers, .key) so others won't have to rediscover the issue. (This will work for non iWork files as well.)
If you are pulling iWork files from iCloud, you need to worry about two primary things before you can get a valid NSData object. A) Security scope through a NSFileCoordinator object (as covered by #cescofry) and B) that iWork files are actually directories/bundles not single files. The options parameter you want for coordinateReadingItemAtURL: is NSFileCoordinatorReadingForUploading. This will read in single files as if you had used 0, but will turn directories into zip files automatically. Strip off the .zip that is added on and you'll have a valid Pages/Numbers/Keynote file. (It's valid with it on too.)
[url startAccessingSecurityScopedResource];
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
NSError *error;
__block NSData *fileData;
[coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
// File name for use in writing the file out later
NSString *fileName = [newURL lastPathComponent];
NSString *fileExtension = [newURL pathExtension];
if([fileExtension isEqualToString:#"zip"]) {
if([[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"pages"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"numbers"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"key"] ) {
// Remove .zip if it is an iWork file
fileExtension = [[newURL URLByDeletingPathExtension] pathExtension];
fileName = [[newURL URLByDeletingPathExtension] lastPathComponent];
}
}
NSError *fileConversionError;
fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingUncached error:&fileConversionError];
// Do something with the file data here
}
[url stopAccessingSecurityScopedResource];
Relevant Apple documentation on the NSFileCoordinator options here:
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSFileCoordinator_class/#//apple_ref/c/tdef/NSFileCoordinatorReadingOptions
A URL from a document picker needs to be accessed through a file coordinator. Further more the url needs to be looked in scope:
[url startAccessingSecurityScopedResource];
__block NSData *data
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
NSError *error;
[coordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
data = [NSData dataWithContentsOfURL:url];
}];
[url stopAccessingSecurityScopedResource];
More from the Apple documentation
The problem was that actually Page documents (*.pages) are not files, but folders. So when I have tried to get NSData from folders path it returns nil.
Default Mail.app attaches documents as zip archives.

how to download jpg,png,pdf,doc.ppt,rtf,etc file from the google drive in objective c

I am new iPhone developer.I am developing iPhone app in this app Google drive integration it is successfully.but I want to download jpg,png,pdf,doc.ppt,rtf,etc file are download.
all file and folder display in Table view.I want do download the selected file from the table view.so how can do this ?
I am read this link https://developers.google.com/drive/v2/reference/files/get but i can not understand.here how to call all this function.
I want to download file's from Google Drive and save in document directory.
I am try this code.
NSString *downloadedString = file.downloadUrl; // file is GTLDriveFile
NSLog(#"%#",file.downloadUrl);
GTMHTTPFetcher *fetcher = [self.driveService.fetcherService fetcherWithURLString:downloadedString];
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error)
{
if (error == nil)
{
if(data != nil)
{
GTLDriveFile *file = [driveFiles objectAtIndex:indexPath.row];
NSString *filename=file.title;
//this variable globalObj.documentPath is global variable for document directory path.
filename = [globalObj.documentPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",filename]];
filename=[filename stringByReplacingOccurrencesOfString:#"file:/private" withString:#"file:///"];
NSLog(#"File name : %#",filename);
NSURL *targetURL=[[NSURL alloc] initFileURLWithPath:downloadedString];
NSData* Data = [[NSData alloc]initWithContentsOfURL:targetURL];
[Data writeToFile:filename atomically:YES];
NSLog(#"my path:%#",filename);
}
}
else
{
NSLog(#"Error - %#", error.description);
}
}];
so places help me.I want to download file and save in document directory.
any link for code places suggestion me.
Thanks
you does not have to do all this stuff.
here is just simple code
image url is from dropbox.
NSString *stringURL = #"https://dl.dropboxusercontent.com/s/pquhnr5pt37uk6q/backkk.jpeg?dl=1&token_hash=AAEXBejAXoD__RPMBom6nL2F5_Uhu62ed0puhtLIt2FGug";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"yourfile.png"];
[urlData writeToFile:filePath atomically:YES];
}
and finally you can represent it any way you want.
If you want to download large data.then use Threading concept.
if you use imageview programetically then write below code..... myimg=[[UIImageView alloc]initWithFrame:CGRectMake(30, 100, 100, 100)];
myimg.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://dl.dropboxusercontent.com/s/pquhnr5pt37uk6q/backkk.jpeg?dl=1&token_hash=AAEXBejAXoD__RPMBom6nL2F5_Uhu62ed0puhtLIt2FGug"]]];
[self.view
addSubview:myimg]; it's working

ios , Attach Audio file aac format to Email

i try to send a audio record by file aac (kAudioFormatMPEG4AAC) format but the file attached it's doesn't send
*myString = file://localhost/private/var/mobile.......
here is my code
MFMailComposeViewController *picker =
[[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"My Audio File"];
NSString *fileName = #"Rec.aac";
NSString *documentsDirectory = myString ;
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *data = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:data mimeType:#"audio/aac"
fileName:fileName];
NSString *emailBody = #"AAC format sound file attached.";
[picker setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:picker animated:YES];
[picker release];
NSData *data = [NSData dataWithContentsOfFile:path];
You're passing in a file:// URL, which won't be understood by that method. That method expects just a standard file path, i.e. /private/var/mobile/.
You could simply use the file path, but if you're only provided with a URL form string, you can create a URL object and use that with NSData.
NSURL* fileURL = [NSURL URLwithString:myString];
NSError* error = nil;
NSData* data = [NSData dataWithContentsOfURL:fileURL options:0 error:&error];
if (error) {
NSLog(#"Unable to load file from provided URL %#: %#", myString, error);
}

Resources