Convert NSMutableData to NSData in Swift - swift

I have a method which is returning NSMutableData. I need to pass this NSMutableData to another method but that method is expecting only NSData. I am trying to find any method/solution to convert NSMutableData to NSdata. But still no luck.
In Objective C, it can be done like this
NSData *immutableData = [NSData dataWithData:mutableData];
I am not sure how it can be done in Swift?Can someone help me in this?

Simply pass the NSMutableData to any method that expects NSData. Since it's a subclass, it will work fine.
But if you really want to do the conversion, simply do (Swift 3):
let data = someNSMutableDataVariable.copy() as! NSData
or
let data = NSData(data: someNSMutableDataVariable as Data)
It may make sense to update your code to use Data instead of NSMutableData or NSData. Just like using String instead of NSString and NSMutableString.

Related

NSData/UIImage to String

Is it possible to convert NSData/UIImage Data Representation as JPEG to a String, to be sent over HTTP to a PHP File to save this string in a database, and then retrive it later on in the application and convert it back into an NSData/UIImage Object?
I have tried Base64 Encoding Libraries but base64 doesn't seem valid as the image doesn't display correctly on a HTML Page.
Any suggestions?
Edit.
I was using the following library:
http://www.imthi.com/blog/programming/iphone-sdk-base64-encode-decode.php
And converting in the following way:
NSData *imageData = UIImageJPEGRepresentation(MyImage.image, 90);
[Base64 initialize];
NSData *encoded = [Base64 encode:imageData];
NSLog(#"%#",encoded);
This does chug out alot of BASE64 but when I save it to a file and try to view it, I just get the eror loading image [?] in Chrome.
Thanks
The point of encoding an NSData object to base 64 is so you can represent the data as a string that can be stored or transferred more easily. You then need to decode the base 64 encoded string back into NSData. This data can then be used to create a new UIImage. Your server needs to do this decoding to get back the original data.
Your code has a mistake. This line:
NSData *encoded = [Base64 encode:imageData];
should be:
NSString *encoded = [Base64 encode:imageData];
Notice that you get back a string, not data.
You commented that you wrote the encoded string to a file then couldn't view the image. Of course not. If you want to write the image data to a file so the file is actually viewable as the image, then don't encode the data first. Write the raw image data to a file.
you can convert image to string like this
first convert your UIImage to NSData & then convert that ata into string by using encodeBase64WithData
NSString *imageOne = [self encodeBase64WithData:[imageDict objectForKey:#"ImageOne"]];
and again string to UIImage like this:
[UIImage imageWithData: [self decodeBase64WithString:[registerDataDict objectForKey:#"imageOne"]]];
You need to import Base64.h
You can directly use like this way:
UIImage *image = _btnaddCountryIcon.imageView.image;
NSData *imageData = UIImagePNGRepresentation(image);
NSString *base64 = [Base64 encode:imageData];
directly you can convert to NSString. This code works fine for me.

How to convert UIImage to JSON file in iPhone?

I have been using NSJSONSerialization class for converting fields of my object to JSON. Sadly only NSString, NSNumber, NSArray, NSDictionary, or NSNull types are supported.
As my object has one additional field, that is UIImage, I am at loss as to how to deal with it. I am sure many people have encountered this common problem, so what is best method to approach this?
You can encode UIImage data by base64, and add it to json object.
To get data from UIImage, you can use UIImagePNGRepresentation and UIImageJPEGRepresentation.
The code like this,
NSData *imageData = UIImagePNGRepresentation(image);
NSString *base64encodedStr = base64encode(imageData);
[dict setObject:base64encodedStr forKey:#"myImage"];
//then covert dict to json object.
To restore UIImage data, just parse json object and decode the data by base64.
Hope this can help you.
You could convert your images data to a string and then write that string.
NSData *imageData = UIPNGRepresentation(image);
NSString *imageString = [[NSString alloc] initWithData:imageData encoding:NSUTF8StringEncoding];
//I don't know how to use NSJSONSerialization
//[NSJSONSerialization serializeString:imageString];
NSString *base64encodedStr = [imageData base64Encoding];

How can I save NSData to my database

I have a object of UILabel
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
label1.text = #"LABEL AREA";
I want to save it in my databse(sqlite).
My idea is to convert this object to a NSData using
[NSKeyedArchiver archivedDataWithRootObject:label1]; //step1
and convert this NSData to a NSString(step2), then save that NSString to the database(step3).
When I need my UILabel. I can get the NSString from database, convert it to NSData, and use
[NSKeyedUnarchiver unarchiveObjectWithData:];
to get my UILabel.
But I have a problem in "step 2". When I use
NSString *strWithEncode = [[NSString alloc] initWithData:dataRaw encoding:NSUTF8StringEncoding];
I get a null object. I don't know the reason.
Why?
Thanks a lot!
You could either a) Store the data as a BLOB or b) Store the text of the string instead of the actual string. B seems like a better choice because you will be storing less data, and the contents of the DB will be human readable, should you need that information for debugging later on.
Because the NSData represents an encoded UILabel and not a UTF-8 encoded NSString, trying to initialize a UTF-8 string from the data will almost certainly not work. If you absolutely have to store the data as a string, try using some form of data-to-string encoding. Try using base32 or base64.

ABPersonSetImageData doesn't display image

I use ABUnknownPersonViewController to display a contact view.
I try to set an image with:
NSData *dataRef = UIImagePNGRepresentation([UIImage imageNamed:#"contact3.png"]);
ABPersonSetImageData(newPersonViewController.displayedPerson, (CFDataRef)dataRef, nil);
It doesn't work and I don't know why. Any ideas?
You can't just cast an NSData object to a CFDataRef; as noted in the docs, a CFDataRef is a "reference to an immutable CFData object", which is not the same as an NSData instance:
typedef const struct __CFData *CFDataRef;
To create the CFDataRef from the NSData instance, you need to use the CFDataCreate method, passing the bytes and length:
NSData *dataRef = UIImagePNGRepresentation([UIImage imageNamed:#"contact3.png"]);
CFDataRef dr = CFDataCreate(NULL, [dataRef bytes], [dataRef length]);
Note also that since you create the object yourself, you must also release it, following the Core Foundation Ownership Policy; you use the CFRelease function to release ownership of the Core Foundation object:
CFRelease(dr);
This is similar to the Memory Management in Cocoa, and once the retain count of the Core Foundation object reaches zero it will be deallocated.
Edit: Stefan was completely right, in his comment, that NSData and CFData are also toll-free bridged on the iPhone with Cocoa-Touch as with Cocoa, so my original answer was wrong. My fault, should have edited it before.

converting NSMutableData to NSMutableDictionary?

i am accumulating data from NSMutableDictionary to NSMutabledata like
NSMutableData *data = [receivedData objectForKey:#"tag1"];
and also
data = [receivedData objectForKey:#"tag2"];
after this one , how can i get data for #"tag2" only from NSMutableData?
NSMutableData tag2Data = [Data forKey:#"tag2"];
is not working?
I'm unsure exactly what you are trying to do here, but it doesn't look like you are using the proper class. If you check the class reference from Apple there is a link to a great code example of getting a string out of an NSMutableData object, but the only way to access the data inside it is using getBytes.