Im facing an issue of PDF images not displaying in UIWebView
The way of the logic is,
1. UIWebView receives a base64 string
2. Convert the string to NSData
3. Load the NSData to the UIWebView
Here is the part of the code
NSString *b64 = #"JVBERi0xLjMNCiW9vrwNCjEgMCBvYmoNCjw8DQoJL0Jhc2VGb25....";
NSData *d =[[NSData alloc] initWithBase64EncodedString:b64 options:nil];
[uiWebview loadData:d MIMEType:#"application/pdf" textEncodingName:#"utf-8" baseURL:nil];
There is a workaround that i manage to show the images in UIWebView, the workaround is
Copy the base64 string to an online converter to convert it to a pdf file
Export there pdf file again using Mac Application Preview using 'Export as PDF'
Convert the file again to base64 string and display at the UIWebView
But this workaround is not feasible, as i do not have the Preview application in the app
I also notice that, before i 'Export as PDF' in Preview application the pdf is editable such as the images can be drag or deleted.
So my question would be,
Did I implement UIWebView code wrongly?
Is the any library for 'Export as PDF' for iOS application? I did explore around on PDFKit, but it does seem to have any export function
b64 is of type NSString
initWithBase64EncodedData:b64 options:nil needs as first Parameter NSData.
Try:
NSString *b64 = #"JVBERi0xLjMNCiW9vrwNCjEgMCBvYmoNCjw8DQoJL0Jhc2VGb25....";
NSData *d =[[NSData alloc] initWithBase64EncodedString:b64 options:nil];
[uiWebview loadData:data MIMEType:#"application/pdf" textEncodingName:#"utf-8" baseURL:nil];
Or try:
[[PDFDocument alloc] initWithData: d];
to get a Pdf from your base64 string.
Related
I have file.xlsx in my IOS app documents folder. I want to show open this excel file in UIWebview. but i am getting below error,
Error Domain=WebKitErrorDomain Code=102 "Frame load interrupted"
but pdf and CSV files are opening,
I am new to IOS and tried all possible things for it to work i guess from last 2 days. nothing worked out.. please help me
Update: Even if i rename it as file.xls its not opening
below is my code,
NSURL* nsUrl = [NSURL URLWithString:url];
_urlReq = [NSURL URLWithString:url];
[self performSelector:#selector(urlRequestForFile) withObject:nil afterDelay:0];
_webView.delegate = self;
NSURLRequest* request = [NSURLRequest requestWithURL: nsUrl];
[_webView loadRequest: request];
-(void)urlRequestForFile{
self.connection = nil;
NSURLRequest *requestForFile = [NSURLRequest requestWithURL:_urlReq cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:300];
_connection = [[NSURLConnection alloc]initWithRequest:requestForFile delegate:self startImmediately:YES];
_ongingServiceFlag = YES;
}
need help in showing xlsx file inside my IOS app either using UIWebView or is there any other way to show xlsx file inside the app without using third party apps?
Update(Solution):
I am very surprised to see that there is no support for XLSX mentioned even in apple site for UIWebView but actually UIWebView completely supports XLSX format. one thing you need to make sure is to specify the correct 'textEncodingName' value. if your file is stored with base64 binary encoding u have to mention it as textEncodingName:#"base64" otherwise u have to mention as "utf-8"
Below line worked for me:
[webView loadData:urlData MIMEType:#"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" textEncodingName:#"base64" baseURL:nil];
Use QLPreviewController for showing xlsx document in your app. Find the links for the tutorial below.
https://developer.apple.com/documentation/quicklook/qlpreviewcontroller
http://iosdevelopertips.com/data-file-management/preview-documents-with-qlpreviewcontroller.html
https://www.appcoda.com/quick-look-framework/
The .XLSX filetype is based on openXML which is good news! This means it's easily readable, we just need to let the webview know the type, or rather mimeTYPE, of the file we are loading/displaying. According to microsoft the mimetype to use for XLSX (OpenXML) files is:
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
source: https://blogs.msdn.microsoft.com/dmahugh/2006/08/08/content-types-for-open-xml-documents/
To do this we load the data (dataWithContentsOfFile: or dataWithContentsOfURL: or your prefered method) by calling the webView method:
[_webView loadData:<#(nonnull NSData *)#> MIMEType:<#(nonnull NSString *)#> textEncodingName:<#(nonnull NSString *)#> baseURL:<#(nonnull NSURL *)#>]
Example of my working code:
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://mycoolserver.com/file.xlsx"]];
[_webView loadData:data MIMEType:#"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" textEncodingName:#"utf-8" baseURL:nil];
.xlsx File cannot be opened using UIWebView. Though you can load .xls file using UIWebView.
Here is a list of files which you can load using UIWebView
https://developer.apple.com/library/content/qa/qa1630/_index.html
If you want to use .xlsx file, you have to use QuickLook FrameWork which contains QLPreviewController. Your code should be like this -
- (void) initQlController{
QLPreviewController *prev = [[QLPreviewController alloc]init];
prev.delegate = self;
prev.dataSource = self;
[self presentModalViewController:prev animated:YES];
[prev.navigationItem setRightBarButtonItem:nil]; }
Then you have to use the dataSource methods for the same : -
- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
I am trying to read in arabic text that I have contained inside of a .doc file, and use it in my app. Unfortunately, the only way I am able to retrieve the text is if I convert the document into .txt file.
Here is the code I have:
NSError *error = nil;
NSString *path = #"MyArabicDocument";
NSString *root = [[NSBundle mainBundle]pathForResource:path ofType:#"doc"];
NSString *myFile = [NSString stringWithContentsOfFile:root encoding:NSUTF8StringEncoding error:&error];
NSLog(#"my file contents are: %#", myFile);
NSLog(#"error is: %#", error);
The output of my NSString object is (null), and the error I get is:
error is: Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0x7aace470 {NSFilePath=/Users/MyName/Library/Developer/CoreSimulator/Devices/.../data/Containers/Bundle/Application/..MyApp.app/MyArabicDocument.doc}
If I convert my document into an .rtf format, then my output (after changing the extension in the above block of code) is the following:
my file contents are: {\rtf1\ansi\ansicpg1252\cocoartf1347\cocoasubrtf570
{\fonttbl\f0\fnil\fcharset0 LucidaGrande;\f1\fnil\fcharset178 AlBayan;\f2\fnil\fcharset178 GeezaPro;
}
{\colortbl;\red255\green255\blue255;}
\vieww10800\viewh8400\viewkind0
\deftab709
\pard\pardeftab709\pardirnatural
\f0\fs46 \cf0 1
\f1 - \'de\'f3\'dc\'c7\'e1\'f3 \'c7\'c8\'fa\'dc\'e4\'f5 \'c2\'c8\'f3\'f8 \'e6\'f3\'c7\'d3\'fa\'e3\'f5\'dc\'e5\'f5 \'e3\'f5\'cd\'f3\'e3\'f3\'f8\'dc\'cf\'f5
\f0 ~~~
\f1 \'c7\'e1\'e1\'e5\'f3 \'dd\'f6\'dc\'ed \'df\'f5\'dc\'e1\'f6\'f8 \'c7\'e1\'c3\'f5\'e3\'f5\'dc\'e6\'d1\'f6 \'c3\'f3\'cd\'fa\'dc\'e3\'f3\'dc\'cf\'f5 \
...
If I try to use an NSAttributedString object instead of an NSString object, but I still get a (null) value for my NSAttributedString object:
NSDictionary *attrs = #{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType, NSWritingDirectionAttributeName:#[#(NSWritingDirectionRightToLeft | NSTextWritingDirectionOverride)]};
NSAttributedString *text = [[NSAttributedString alloc] initWithFileURL:[[NSBundle mainBundle] URLForResource:#"MyArabicDocument" withExtension:#"doc"] options:attrs documentAttributes:nil error:&error];
The reason why this is important is that while my arabic text does indeed appear in my UITextView in my app, the problem is that it's appearance is nowhere near as nice as in the original document, which is what I would like to maintain in my app. Is this not possible?
.doc file in question is in binary format. (probably compressed like .docx)
http://en.wikipedia.org/wiki/Doc_(computing)
So you cannot put it in NSString as is. But you can get NSData:
NSString *path = [[NSBundle mainBundle] pathForResource:#"MyArabicDocument" ofType:#"doc"];
NSData *data = [NSData dataWithContentsOfFile:path];
Unfortunately you cannot make an NSAttributedString from .doc in iOS, but you can in OS X (in iOS there only four doc types supported)
NSError *attrError;
NSDictionary *options = #{NSDocumentTypeDocumentAttribute: NSDocFormatTextDocumentType};
NSAttributedString *content = [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:&attrError];
Instead you may try to load your .doc file into WebView.
Using NSData:
[self.webView loadData:data MIMEType:#"application/msword" textEncodingName:#"UTF-8" baseURL:nil];
But I think better with NSURLRequest (since you don't nee to set up encoding there)
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
NOTE: Any method you choose very likely will BREAK your format, I mean rendered document will be corrupted. Instead I recommend to convert .doc to .pdf In this case it will be good-loking.
For example Dropbox app for iOS defenetly converts .doc/.docx to pdf and than presented to the user as PDF (Of course not telling that it is PDF indeed).
I think you have a encoding issue when reading a file,
Refer below link
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/readingFiles.html
May be it solve your problem
Best of luck!
As we know with the launch of ios 8 the apple allow custom Keyboard extension.In keyboard extension we can send images,gif etc in SMS by using Copy image to clipboard.code
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
NSData *data= UIImagePNGRepresentation([UIImage imageNamed:#"so_close_disappointed_meme.png"]);
[pasteboard setData:data forPasteboardType:#"public.png"];
Now i am trying to send audio file in iMessage like this feature reference.don't know apple will allow us to send audio in iMessage?.so for i tried above approach but it did not show any paste option for audio in SMS window.
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
NSString *path = [[NSBundle mainBundle] pathForResource:#"tune"ofType:#"mp3"];
NSURL *url = [[NSURL alloc] initWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
[pasteboard setData:data forPasteboardType:#"public.mp3"];
Any one can suggest me how do we send audio file by using custom keyboard extension.is it possible?
I believe you could directly attach the file to MFMessageComposeViewController. Here is the documentation link of how it could be done.
Following would be the steps to do so.
Check if file can be send using file UTI using +
(BOOL)isSupportedAttachmentUTI:(NSString *)uti
Find File UTI. i.e. path for the file
Attach file to MFMessageComposeViewController using -
(BOOL)addAttachmentData:(NSData *)attachmentData
typeIdentifier:(NSString *)uti filename:(NSString *)filename
As the description for the method says
This method is especially useful when the attachment you want to add to a message does not have a file system representation. This can be the case, for example, for programmatically composed audiovisual content.
Note : You will have to convert audio file to NSData
The MFMessageComposeViewController isn't the solution in this scenario. A custom keyboard extension shouldn't present a new view controller, rather just paste the audio file to the pasteboard. Heres some swift code that worked for me
let path = NSBundle.mainBundle().pathForResource("audio", ofType:"wav")
let fileURL = NSURL(fileURLWithPath: path!)
let data = NSData(contentsOfURL: fileURL)
let wavUTI = "com.microsoft.waveform-audio"
UIPasteboard.generalPasteboard().setData(data!, forPasteboardType: wavUTI)
Am having a set of images in document directory path,i need to convert all of my saved images into pdf with page number.am using the following code for converting pdf
UIWebView *webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 64, 320,430)];
pdfData = [PDFImageConverter convertImageToPDF: imageVIew.image
withHorizontalResolution: 550 verticalResolution: 320];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent: #"Documents/new.pdf"];
NSLog(#"path %#",path);
[pdfData writeToFile:path atomically:NO];
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]];
[self.view addSubview:webview];
In this code i can able to convert a single image into pdf.How to convert all of my images into pdf ?
Here is the tutorial to generate PDF from image and other assets: http://code.tutsplus.com/tutorials/generating-pdf-documents--mobile-11265 worked for me always.
I wanted to show a gif so what i did was that i split my gif and showed it in a animation for UIImageView using this link.
http://iphonenativeapp.blogspot.com/2011/03/how-to-show-animation-in-iphoneipad-app.html
Now, i want to make the user copy that gif and paste it in the mail app.
If i used the array which contained all the split images of gif then 4-5 images get pasted in the mail app.
Please help me paste the gif. Thanks!
Gonna copy/paste my own answer from a similar question.
NSString *gifPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:#"volleyball.gif"];
NSData *gifData = [[NSData alloc] initWithContentsOfFile:gifPath];
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
[pasteboard setData:gifData forPasteboardType:#"com.compuserve.gif"];
[gifData release];
Edit just noticed you asked these 2 similar questions yourself.
Although you can use HTML based email -- for example:
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
NSString *emailBody = #"<p><b>Hello World</b></p>";
[picker setMessageBody:emailBody isHTML:YES];
You can't insert inline images as you would typically in HTML. Inline images in HTML email use separate MIME parts that are referenced via a content-id element from the body of the message. MFMailComposeViewController doesn't give you control over the MIME structure of the message and thus doesn't let you add inline referenced content parts.
Embedding image data into <img> tags as base64 will sometimes work -- it depends on the email client and browser used to render it -- but it's not broadly portable.
FWIW, animated gifs appear to work with email in the new share sheets in iOS 6, which would automatically populate the gif in an email if the user selects mail:
NSString *gifPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:#"volleyball.gif"];
NSData *gifData = [[NSData alloc] initWithContentsOfFile:gifPath];
NSArray *activityItems = [NSArray arrayWithObjects:#"Here is an awesome body for the email.",gifData,nil];
UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
activityController.completionHandler = ^(NSString *activityType, BOOL completed){
// item was shared!
// you can check if it was email (or another type, like facebook or twitter) in the *activityType.
// completed is YES if they actually shared it, if they canceled, completed will be NO.
};
[navigationController presentViewController:activityController animated:YES completion:nil];
As iOS does not support the animated GIF format, I don't think it is possible to copy/paste the gif in the mail app. However, you can try attaching the gif file (not the split images) & composing a new email using MFMailComposeViewController. If you open the attachment on a non-iOS device, you should be able to see the animated GIF.
HTH,
Akshay