Converting between NSData and base64 strings - ios

What is the easiest and fastest code to do a conversion between NSData and a base64 string? I've read a bunch of solutions at SO and mostly they involve in adding another class etc. I found a great solution here but it's too complex.

Scroll down to the Conclusion section on the page you linked and download the provided NSData+Base64 files. Its the best solution I have seen so far and is incredibly easy to use. If you can learn anything about Cocoa, you can learn to use that project.
Example
NSString *originalString = [NSString stringWithFormat:#"test"];
NSData *data = [NSData dataFromBase64String:originalString];
NSLog([data base64EncodedString]);
The above will print out the original string after converting it to base64 and back to a normal unencoded string.

As of iOS 7, NSData now directly provides this functionality with the new methods -base64EncodedDataWithOptions: and -base64EncodedStringWithOptions:. (The options let you specify that the string is/should be line-wrapped, the better to deal with email, and user-facing displays.)

You don't need any custom implementation. Creating base64 from NSData is shown in other answers. There is opposite direction. From Base64 string to NSData:
NSString *base64Encoded = #"some base64 string";
NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:base64Encoded options:0];

I ended up using this same class as provided by SUDZC
implementation was easy first I did an import
#import "NSData+Base64.h"
then I was able to call my data.
NSData *data = [[NSData alloc] initWithData:[NSData dataWithBase64EncodedString:strData]];

Be aware that there are more Base64 formats.
For example JWTs use a URL safe format.

Or you may take a look to the (quite new) CryptoCompatibility sample project, I think there is a wrapper class for base64 operation. It is a MacOS sample but it uses the library libresolve.dylib with I think is available on iOS too (is see it at least here in iOS7).

Related

split string in ios string from json data?

I have one string. Now I wanted to split this string. For static separation I know the code but I don’t code for dynamic value.
my string is
NSString *str = #"https://graph.facebook.com/v2.5/181054825200000/feed?fields=created_time,message,picture,full_picture,comments.limit%280%29.summary%28true%29,likes.limit%280%29.summary%28true%29&limit=5&format=json&access_token=CAALjFrE5mNYBAOg1EDiUrsE2kr1kIRrLIv7g4OweSMvHso2exB5Dttshn7dgOlW24ZCXSnDZAWiV6xMUKXedTXUhiHpdmZBPCGzD1orFlrLRP2gaBZCbZBZBnjUHewF9hZBmJKxtiwVzpw9gnnQXk5Hfx0ZBM2ksAUzkSWR5feaNMbf3UUmUpJlxeh0gKdDrzWBvIJRPy0xGqL0ZAMFsRhyCZCTX42l1sZAceZB0VCeDZB95mrAZDZD&until=1456345291&__paging_token=enc_AdCKD3tSYMoZB3MCKaJkYnbVmBgUyY2tBceGDD2G1hqxRDiQKZCsSbmvWZASLvlCMf0BVzq2uZAScSWp7ZAavZB2d72BIHJISefk09noRuv9gA5b5hFwZDZD";
but i don’t how to show any value dynamically .(for e.g. until (in string))
please help me for this issue.
Thank You.
If you are parsing a URL you should really use NSURLComponents. It makes breaking a URL into the different parts much easier, and the code is tested and verified by Apple.
For separate string by a separator you can use this.
NSString *url = #"<url>";
NSArray *array = [url componentsSeparatedByString:#"<seperator string>"];
NSLog(#"%#", array);
But for URL parsing ,As per Duncan's answer, yes it is good to parse a URL using NSURLComponents. By using this class you can get any desired part of an URL.

Connect this NSSting with a String Variable

All I want is to change every time the NSString townLocation.
Because I take data from an API and I don't want to create different API for different location. Also I know that the "+" that I put on the link is not correct and there is not such think in Objective C but I want to make you understand what I want.
NSString*townLocation;
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://api.openweathermap.org/data/2.5/find?q="+townLocation+"&units=metric"]];
How I must do it ? Im sure you understand that I'm new at Objective C
Thank you
You only need to look into the most basic NSString documentation to find a method that will do that, stringWithFormat:.
NSString *urlString = [NSString stringWithFormat:#"http://api.openweathermap.org/data/2.5/find?q=%#&units=metric", townLocation];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
If you're new at Objective-C, a good place to find information like this is to simply search the internet or the iOS Developer Library for the class in question (in this case, NSString) to find a myriad of resources at your disposal. Another doc to check would be Formatting String Objects, which is linked in the stringWithFormat: section of the iOS Developer Library, to find more info about formatting strings.

Failed to read the gzip compressed string in Objective-C?

As the title says,i am using GZip to compress and decompress the string.But in between that i want to read the compressed string,how do i read that unknown compressed string?.
What i tried so far:
Using GZip(from github),i tried compressing the string as below...
//UML string
NSString *plantUmlString = #"#startuml\n Bob -> Alice : hello \n#enduml"
String compression...
NSData *originalData = [plantUmlString dataUsingEncoding:NSASCIIStringEncoding];
NSString *compressedString = [[originalData gzippedData] base64EncodedStringWithOptions:kNilOptions];
NSLog(#"%#", compressedString);//H4sIAAAAAAAAA8tIzcnJV0gvrSwuKcrMSw8tBhKuecn5KQCRj54cGQAAAA
Where i am struggling:
compressedString is returning "H4sIAAAAAAAAA8tIzcnJV0gvrSwuKcrMSw8tBhKuecn5KQCRj54cGQAAAA"
instead of "SzIrIxBAICt9oGS0",this is the actual string i should get.If i decode the generated compressedString,i am getting nill...And if i use UTF-8 encoding i am getting "null"..How do i read the actuall string here?
NOTE: if i decompress the above compressed data,i am getting original string before compressing...
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:compressedString options:0];
NSString *decompressedString=[[NSString alloc] initWithData:[decodedData gunzippedData] encoding:NSASCIIStringEncoding];
NSLog(#"%#",decompressedString);
//Correct: decompressedString returning me the original string before compressing...
What i am trying to do:
Trying to generate a flowchart using the PlantUML Server,which accepts the compressed UML string and returns me the flowchart image...
Some more information : If i compress the above UML string in android(which is available in github) i am getting "SzIrIxBAICt9oGS0" as the string...But in Objective-C i am reading entirely different string...
Am i doing something worng with the encoding?...Any advice/solution is really helpful...
According to the sample code at http://plantuml.sourceforge.net/codephp.html , it uses compression level 9, so you probably want to use that, if you want to exactly match that string.

Can I create an NSURL that refers to in-memory NSData?

The docs for NSURL state that:
An NSURL object represents a URL that can potentially contain the
location of a resource on a remote server, the path of a local file on
disk, or even an arbitrary piece of encoded data.
I have a blob of in-memory data that I'd like to hand to a library that wants to load a resource via an NSURL. Sure, I can first write this NSData to a temp file and then create a file:// NSURL from that, but I'd prefer to have the URL point directly to the buffer that I already have present in memory.
The docs quoted above seem to suggest this is possible, but I can't find any hint of how to accomplish it. Am I missing something?
NSURL supports the data:// URL-Scheme (RFC 2397).
This scheme allows you to build URLs in the form of
data://data:MIME-Type;base64,<data>
A working Cocoa example would be:
NSImage* img = [NSImage imageNamed:#"img"];
NSData* imgData = [img TIFFRepresentation];
NSString* dataFormatString = #"data:image/png;base64,%#";
NSString* dataString = [NSString stringWithFormat:dataFormatString, [imgData base64EncodedStringWithOptions:0]];
NSURL* dataURL = [NSURL URLWithString:dataString];
Passing around large binary blobs with data URLs might be a bit inefficient due to the nature of base64 encoding.
You could also implement a custom NSURLProtocol that specifically deals with your data.
Apple has some sample code that uses a custom protocol to pass around image objects: https://developer.apple.com/library/mac/samplecode/SpecialPictureProtocol/Introduction/Intro.html#//apple_ref/doc/uid/DTS10003816
What you are missing is the NSURLProtocol class. Takes about three dozen lines of code, and any code that handles URLs properly can access your in-memory data. Read the documentation, it's not difficult and there is sample code available.
Unfortunately there are some APIs that take an NSURL as a parameter, but can only handle file URLs.

hide registration code from user on iOS

Only a short question here, I would like to know the best place to put my registration code for the user that I get back from the server. I am encrypting it as seen here.
//encrypting
NSString* strToEncrypt =NewPINField.text
NSString* theKey = #\"KeyKeyKeyKey\";
NSData* dataToEncrypt = [strToEncrypt dataUsingEncoding: NSUTF8StringEncoding];
NSData *encryptedData = [dataToEncrypt EncryptWithKey: theKey];
NSLog(#\"Encrypted data: %#\", encryptedData);
//decrypting
NSData* encryptedData = (NSData*)[profileData objectForKey:#\"PIN\"];
NSString* theKey = #\"KeyKeyKeyKey\"; //notice this is the same as above. It MUST be
NSData *decData = [encryptedData DecryptWithKey: theKey ];
currentPIN = [NSString stringWithUTF8String:[decData bytes]];
NSLog(#\"Decrypted pin: %#\", currentPIN);
The only other specification is to hide it / put it somewhere no know would think to look.
I need to save state so it needs to be some sort of plist, I was just wondering if there is a way to hide it a little better than just adding it straight to my plist file.
what would you do?
Any help would be greatly appreciated.
If you need to securely store data, I would highly recommend using the keychain. There is a tutorial on creating a basic keychain app here: http://www.raywenderlich.com/6475/basic-security-in-ios-5-tutorial-part-1
You can safely store data in the keychain without worrying about encrypting it first, since that is handled by the OS. But you can if you want to.
When implementing security, never try to hide things where someone won't look: http://en.wikipedia.org/wiki/Security_through_obscurity

Resources