How to convert the binary to pdf file on iPhone? - objective-c

I receive a binary pdf file, which is base64Binary encoded.
How can I convert it back on the iPhone? What tool kits can I use?
Thanks.

Solved:
NSData theData = [NSData dataWithData:[GTMBase64 decodeString:theBinary]]; //first transfer it to NSData.
[m_oTestingWeb loadData:theData
MIMEType:#"application/pdf"
textEncodingName:#"UTF-8"
baseURL:nil]; //using the web view to show it back

Solution
NSString *binaryString = [myDict objectForKey:#"key"];
NSData* myData = [NSData dataFromBase64String: binaryString];
NSLog(#" %#",datas);
[self savePDF:myData];
and save PDF is like this
- (void)savePDF:(NSData *)pdfContent
{
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:#"myPdf.pdf"];
NSLog(#"%#",finalPath);
NSURL *url = [NSURL fileURLWithPath:finalPath];
[pdfContent writeToURL:url atomically:YES];
// [aWebView loadRequest:[NSURLRequest requestWithURL:url]];
}
Get headers here.

If you mean NSData by the word "binary" then you can follow the following method.
I think if the binary data is already in PDF format then we can just use the normal NSData method to writeToFile:atomically to write it to the file.
[<NSDataObject> writeToFile:<FilePath> atomically:YES];
And then you can use the DocInteraction to open and display a PDF File.
Hope this helps you.

To convert a binary (base64 pdf string) to pdf and show it you can do this for Swift 3:
// Here you convert the binary base 64 pdf string to pdf
let pdfData = Data(base64Encoded: theBase64PDFString, options: .ignoreUnknownCharacters)
// here you can display the pdf on a UIWebView
webView.load(pdfData!,
mimeType: "application/pdf",
textEncodingName: "UTF-8",
baseURL: URL(fileURLWithPath: ""))

To display a PDF, you can simply use a UIWebView and feed it the PDF. If you want it a little more sophisticated, look at Apple's ZoomingPDFViewer sample code (found that one in an answer to another question).

Visit this site base64 encoding. Here You will get code for decoding base64 data to NSData. Using that data you can save pdf, view pdf using UIWebView or using Quartz Core.

To convert the binary into a PDF file
#IBOutlet var pdfView: PDFView!
guard
var fileURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last,
let convertedData = Data(base64Encoded: data.base64EncodedData()) // data is the binary pdf
else {
// handle error when getting documents URL
return
}
fileURL.appendPathComponent("filename.pdf")
do {
try convertedData.write(to: documentsURL)
} catch {
// handle write error
}
Bonus: View the PDF without deprecated UIWebView API
let pdfView = PDFView(frame: self.view.bounds)
self.view.addSubview(pdfView)
// Fit content in PDFView.
pdfView.autoScales = true
pdfView.document = PDFDocument(url: fileURL)
Maybe it's a bit late, but I hope it will help someone else at least.

Related

Convert data from URL into Image in iPhone

Here I'm working for static URL.
My Code :
NSURL *url = [[NSURL alloc] initWithString:#"http://cns.bu.edu/~lgrady/diagonal_line_nobreak_seg.jpg"];
NSData *myData = [NSData dataWithContentsOfURL:url];
img.image = [UIImage imageWithData:myData];
So, I can see image in ImageView.
But, While passing internal web-service URL.
And I'm getting data for Image in bytes from url instead of Image like below:
{"AppBanner":"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUg.....VORK5CYII="}
But with help of above code, I can't convert this data into Image.
So how can I convert this data into image ?
Any Solution ?
Thanks in advance.
Use NSData-Base64 to convert base64 into NSData and then into UIImage
NSString *strBase64 = [yourResposeDict objectForKey:#"AppBanner"];
//decode strBase64 using NSData-Base64 library

Embedding XML to iOS application

I'm making my first game in iOS and I need to load some levels that are stored as XML. Level files are stored locally and everything works fine from emulator. However, since XML is loaded in the runtime when i try to test my game on an actual device it can't find the XML files since they are not actually part of the app.
I'm coming from Flash background so I might have a wrong idea how this is done on iOS but I need to somehow bundle those XML files with the app, or embed it in the code somehow? Is this possible?
Thanks a lot :)
Well The code to look up your app bundle for the specified file is
NSString *path = [[NSBundle mainBundle] pathForResource:#"fileName.xml" ofType:nil]
NSURL *xmlURL = [NSURL fileURLWithPath:path];
[[NSXMLParser alloc] initWithContentsOfURL: xmlURL]
Hope this helps you...
You could add the XML file to your project and run time read it up with something like this
NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *myPath = [myPathList objectAtIndex:0];
NSError **err;
myPath = [myPath stringByAppendingPathComponent:fileName];
if([[NSFileManager defaultManager] fileExistsAtPath:myPath])
text = [NSString stringWithContentsOfFile:myPath encoding:NSUTF8StringEncoding error:err];
You could consider using JSON in instead of XML. At least to my knowledge the available XML parsers are not nearly as simply to use as SBJson for instance (https://github.com/stig/json-framework/)
Here is my solution in Swift 3.0. In addition to the code, you'll need to add your xml file as a data set in your Assets.xcassets. Do this by creating a new Data Set, giving it any name, and then dragging the xml file from the finder to your newly created data set. When you reference the file in your code, you'll use the file name of the file, and not the name of the data set.
var parseResults = false
if let path = Bundle.main.path(forResource: fileName, ofType: ".xml") {
let url = URL(fileURLWithPath: path)
if let xmlParser = XMLParser(contentsOf: urlToFile) {
xmlParser.delegate = self
parseResults = xmlParser.parse()
}
}

objective c - does not read utf-8 encoded file

I'm trying to display some japanese text on the ios simulator and an ipod touch. The text is read from an XML file. The header is:
<?xml version="1.0" encoding="utf-8"?>
When the text is in english, it displays fine. However, when the text is Japanese, it comes out as an unintelligible mishmash of single-byte characters.
I have tried saving the file specifically as unicode using TextEdit. I'm using NSXMLParser to parse the data. Any ideas would be much appreciated.
Here is the parsing code
// Override point for customization after application launch.
NSString *xmlFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"questionsutf8.xml"];
NSString *xmlFileContents = [NSString stringWithContentsOfFile:xmlFilePath];
NSData *data = [NSData dataWithBytes:[xmlFileContents UTF8String] length:[xmlFileContents lengthOfBytesUsingEncoding: NSUTF8StringEncoding]];
XMLReader *xmlReader = [[XMLReader alloc] init];
[xmlReader parseXMLData: data];
stringWithContentsOfFile: is a deprecated method. It does not do encoding detection unless the file contains the appropriate byte order mark, otherwise it interprets the file as the default C string encoding (the encoding returned by the +defaultCStringEncoding method). Instead, you should use the non-deprecated [and encoding-detecting] method stringWithContentsOfFile:usedEncoding:error:.
You can use it like this:
NSStringEncoding enc;
NSError *error;
NSString *xmlFileContents = [NSString stringWithContentsOfFile:xmlFilePath
usedEncoding:&enc
error:&error];
if (xmlFileContents == nil)
{
NSLog (#"%#", error);
return;
}
First, you should verify with TextWrangler (free from the Mac app store or barebones.com) that your XML file truly is UTF-8 encoded.
Second, try creating xmlFileContents with +stringWithContentsOfFile:encoding:error:, explicitly specifying UTF-8 encoding. Or, even better, bypass the intermediate string entirely, and create data with +dataWithContentsOfFile:.

PDF writing from iPad

I am able to generate a PDF with the following code. Can someone please help me with how I would add text to this? Thanks in advance.
-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
UIGraphicsBeginPDFPage();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[aView drawRect:aView.bounds];
// remove PDF rendering context
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(#"documentDirectoryFileName: %#",documentDirectoryFilename);
}
I've never done this (yet, I plan getting on it tomorrow). But I think the right place to go is the Quartz 2D programming guide. It's also available from your developer documentation if you need it offline.
Basically you the same as you posted but appart from calling drawRect: you perform all the text drawing you want on that context.
There's useful information on writing simple strings on this guide
I hope it helps. It sure helped me!

TIFF image format for iphone application

I am working on iphone app and i need to save image into .tiff format.
It is possible to save image into png format using UIImagePNGRepresentation method and JPEG format using UIImageJPEGRepresentation. But i need to save signature captured by imageview into tiff format.
I unable to use NSImage class so that i can call TIFFRepresentation method.
How can i do it.Send me suggestion...
Thanks in advance...
I don't know what you mean by "captured by imageview". The means to save as TIFF wasn't introduced until iOS 4. Here is example code to save an arbitrary file as a TIFF; you can do this with any file-format data, no matter how you obtained it. You need to link to ImageIO framework and do #import <ImageIO/ImageIO.h>:
NSURL* url = [[NSBundle mainBundle] URLForResource:#"colson" withExtension:#"jpg"];
CGImageSourceRef src = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
NSFileManager* fm = [[NSFileManager alloc] init];
NSURL* suppurl = [fm URLForDirectory:NSApplicationSupportDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:YES error:NULL];
NSURL* tiff = [suppurl URLByAppendingPathComponent:#"mytiff.tiff"];
CGImageDestinationRef dest = CGImageDestinationCreateWithURL((CFURLRef)tiff,
(CFStringRef)#"public.tiff", 1, NULL);
CGImageDestinationAddImageFromSource(dest, src, 0, NULL);
bool ok = CGImageDestinationFinalize(dest);
NSLog(#"result %i", ok); // 1, all went well
// and don't forget memory management, release source and destination, NSFileManager
[fm release]; CFRelease(src); CFRelease(dest);
Hmm, I don't develop for the iPhone, so can't tell you if there's a magic API way of doing this, but many years ago I had to create TIFF images manually.
The TIFF format is a bit whacky if you're used to just using a framework's CreateThisStuffAsAnImage() methods, but you can get the spec here and create the file yourself:
http://partners.adobe.com/public/developer/tiff/index.html#spec