开发者

iPhone/iPad Base64->NSData->PDF how to?

Obj-C or Monotouch.Net C# answers are fine.

I have a Base64 stri开发者_Python百科ng that is a PDF document received over a web service. I can get the NSData.

How do I take the NSData and save it as a PDF?

-- I get the NSData this way --

byte[] encodedDataAsBytes = System.Convert.FromBase64String (myBase64String);
string decoded = System.Text.Encoding.Unicode.GetString (encodedDataAsBytes);
NSData data = NSData.FromString (decoded, NSStringEncoding.ASCIIStringEncoding);


The simplest way to save it is probably to use NSData's writeToFile:options:error: method.


I found that using the .NET framework works better than trying to use the iOS framework for this problem. This will take any file and convert it to it's original then save it to the iPhone/iPad device. "path" is just a folder on the dev ice.

using (var f = System.IO.File.Create (path))
{
   byte[] encodedDataAsBytes = System.Convert.FromBase64String (Base64PDFString);
   f.Write (encodedDataAsBytes, 0, encodedDataAsBytes.Length);
}


I'm working on a project where I recently had to accomplish the same thing you are describing. I get base64 encoded PDF files as strings from a .NET web service which need to be decoded to their original and saved as PDF files in the applications documents directory.

My solution was:

  1. Use ASIHTTPRequest to communicate with the web service.
  2. I then use TBXML to parse incoming xml and get the base64 as an NSString.
  3. To decode the string I use a method from QSUtilities library called decodeBase64WithString.
  4. Finally I save the result with NSData's writeToFile.

I have tested and successfully used this method with PDF files that are up to 25mb. I also had a couple of test runs with a 48mb file but that file made the decodeBase64WithString method take up too much memory and my app crashed. Haven't found a solution to this yet..

If you are working with multiple large files be sure to free up your memory once in a while. I got all my files in one loop in which I had to use my own nsautorelease pool and drain it at the end of the loop to free up any autoreleased objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜