How do I convert NSData to file format (.mp4/.m4a) - ios

I have some NSData variables which contain .m4a/.mp4 file formats. I've tried looking at ways to convert the NSData into file format, with no luck. I need to convert it into a file, change some of it's metadata, and convert it back to NSData. Here's some code:
// This JSON basically gets the url of a .m4a
NSArray *preview = [JSON valueForKeyPath:#"results.previewUrl"];
_previewData = [NSMutableData dataWithContentsOfURL:[NSURL URLWithString:[preview objectAtIndex:0]]];
[_previewData writeToFile:path atomically:YES];
ANMovie* file = [[ANMovie alloc] initWithFile:_previewData]; // or .mp4
NSData* jpegCover = UIImageJPEGRepresentation(artworkImage, 1.0);
ANMetadata* metadata = [[ANMetadata alloc] init];
metadata.albumCover = [[ANMetadataImage alloc] initWithImageData:jpegCover type:ANMetadataImageTypeJPG];
[file setMovieMetadata:metadata];
[file close];

I'm guessing [[ANMovie alloc] initWithFile:] expects a file, and you've passed it, I'm also assuming here, an NSData*.
Try:
ANMovie* file = [[ANMovie alloc] initWithFile:path];

Related

Converting sqlite3_column_blob to NSString

I have been trying to add sqlite3_column_blob type of value to NSString by this lines of code :
NSUInteger len = sqlite3_column_bytes(compiledStatement, n);
NSData *cData = [[NSData alloc] initWithBytes:sqlite3_column_blob(compiledStatement, n) length:len];
NSString *columnText = [NSString stringWithUTF8String:[cData bytes]];
Here is the BLOB data which i am trying to retrieve from the database :
�PNG
IHDRXXq�04sBIT|d�
�IDATx��{pEǿ� !�f��E���0��#����Q'p#iQ��È�L�P���R`6 F�COJD�q��0 ��\�FbrȁR�������c6��������f�����M��-����n"�~;�p0s��bɶX,c�U^7!�Q!��e�n�2��o�%��#���~3G!�^�X,��<�b��B\S�)ˬ`��Ť*S��#�.�9+c�8ADtN�fd�}����D4��̊�X����u9��f�y̜/_�c�
"J�D�V0�^"�0��h6��Du��,3s83���f"z��j���6M]!V�[q���\��+��O�QUU�K�.*~:���#HH�|�]�F�#tt�'�C�$wU�+<ט�� >}���`��rR�b<�sv��\��'Nb�8~�$��F��h����<z$��1�U{�J�t#'9��~e��X|*�b�I��]��+�:|F��B��6$IB��~xd��>aa����$�/�j��f�H��
rV����ز{>��ju1�Q��'�E�+}Q�/^��&����r�۰Ǿ>����A�:g�S��(��r}Q�Of���
��t��omƶw5Y7�-�$aꔉH�5]��>KD�}1�J`f0#7!DM`7u=p�0Vg��ҥ_��&%,�2^L�#Æ��ʘ�CI�*�8HD���-03�oko��7n"7�mߥ�ѷ���'b��9v:r='���z�������V^ͅ_���E�%z����bU�rt���|"z����y���ݴ��+0��y+.�`��P^^ᬈ�ow�n����S�� %5���[O�t�W������3yB�:]3s["�L;u��g4z�O��uH[�� 2=.�=ƣ>��;x��gA1+/�#JjZ�W����u&DG�����l%�jw�p)03��h�:���/�����^���"<�nl|#O����[$I��jdᮋ��%�7����ŋ���4�eܸq�!O�f���ݙ+;h%��o�z�зOO�I�1����`��g��*�yȫg���pd�x�v]__�=��Ǟ��4?^�()-Gn�,yA�(���wo��A���G��D��Sv&&No'.,9�����J����/�ۥL�0��L����s�m߅ke�4ڻ��.j6�aUV�ΦݢW�D�V!$$D3?$$��L�̞�j6���6H�=��L�u�Vy-r֚��z�7u�K۱K�����u6z���Ꙉ��?�Jpp̚��{�M����Xn�hŸ��x�71k�Sn�8!!!����M����
oۥ�5R�9�`�NB��D4˚VRZ��3��m����<���Ǿ>�s�.�����g#d���о���A��ᴨ�����t������
$I���ۙ:��-I�^$"������<�����_X�G��jL���Vy%ns��C�$!絕��+D�X�Zm�E0sof���E�%-N\���/ߴ
=t�w�h��(�3odf;+���Tc���j#���������Sv�n�]hb����nVRUU�lx�I��x��3=�#�Fc(Lٙ���=��[�N��-
m� ,O��V$?��غ'�#oͪ�׊���5�<Y�O?s0
�WO��i�l���
p|\l��k�*r|\�G����v�j�Ǐ���l~
ߝ�5~q[Q|\,^�{-�ŵb4�����<����nBD�d�6������h��9���J��b�o
�7W����8���b�}�y�,03G1s!T.���O�|�U�����h~``4�"�侻(<~R�4���9
�B,`�T__���2�n���.k��Zi߾V������攨 R���E8�7~8W�r�p��M,{e�W�[?�Ѭ� fs�~�ë����R�l�����L���$i=T�_+�6��K0w�R]bm�`rr�y\�W���%��\���zd����$IkY`"�ff�9�?���!zD޶}�m�JN�:�l�z��b����:�(B����.x0<�RT\���]��m�.d����MEV�Z�"��uX�(]׊�Z+I����_�n�TQS����>ۙ��w~��Z��Y��;?qH���ù"]����fذ�"�9SY��o�{�h��}�'X��OP��:+�Ndo��b�L�^=Iv=}#��еk�|�l(E�Wq����Ů�v7J\#S�pf~���3?�̛�%���ѫʬ<y?��+Z���Q�����:�3�i���zB�/҈h���̊7�J��� �Z/� �:'�������)�u"z����Z����rЪ���$��։F%e(K�� �XSӾ��=��2�����`;��=�w7}�Z�Zٴ� ,��sb�׉}+�t����Z��u�AD)�B�{�[q�Z+"J�ƫ�ڃ����V9��
��
!�~�":�Kx�k��'8��3����`I�V�ۛk0�{S�G���Z�q���6{p%8�,�4�o�42���i>IDC��P�"����FC1���^ڊ���(/ˈh�rs�ڳ���[�{$&�kW���t�a��2��DtEY��+FDq��?�m�U�%��F����c���06ƍMnM8a�X��Q��6��������}�1��־X�����>�ѭ�(j�5m�3�;l���q��s�J"���R��9��C�|��#f�Z.Uf"J%"���#D�(���U��I�����&��9��Ҙ�]"�!���BD5AAAO3�m�=6&�&��*~G1i�x���AAAO����f��$I�)����4�X�$,��̴KSk��ݿy;g����a�"�A�Z<K���&u2ҝ���Q����u6-�<����p�,�����V���s�E�kQ��Dc�¹β55��I#�MD�:���)��ZD�W��uB��5�6f�*I�W9<
)`3?�c�R�RfK�Cʨaf�����盓���8åx ���L���,%� N�k�#D�̼[�ֿ_�Yݢ<��֬v0�3�n���tO�$Ir�ڷOO�7��1rXX'�7�o��yZ����}5���Dc�y=���78�v�o�����c���������A��}�Up�b"����A�a~�(!D=���_��\\���a�m��:��%�&̼S��b��]�f#3��Jd��
6���<u�D�I���^&�����b\94L�/�j� �E�%شy���d�a�1}�����$�����ڋ8p�0�-l�c�I���ô�L���c�A%����tE1���wv�m>�d�|P�5T-��~{P�3,�j�X-�����QY�3��+PU]�˗�#JJ�����DC��бct��#��(DFޏ޽=Z�b悠���:j�r��R��aQ1Ζy|I��b�~o/)���g�h�R�!r��XN'���C\����DtV��M>����Z�9�G����L!D�Ƒ�
�%S.��GN�
�CSW4����vhj�v�!P���?� �kɲIEND�B`�
But every time i am getting nil response although there is a value exist. Rest of the parameter values are coming just i am getting nil response in above value.
Thanks.
The reason you cannot convert that data to a string is because it's a PNG image file:
�PNG
(I assume; I haven't looked at the PNG spec to confirm this, it's just an assumption at this stage).
Finally i got the solution for the above issue which i was facing :
NSData *content = [[NSData alloc] initWithBytes:sqlite3_column_blob(compiledStatement, 2) length:sqlite3_column_bytes(compiledStatement, 2)];
NSString *columnText = [content base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

Save and load image from SQL database

I'm trying to display an image from my Database.
This part works nicely.
I save the image in the DB like this :
UIImage *resizedImg = [Generics scaleImage:self.photo.image toResolution:self.photo.frame.size.width and:self.photo.frame.size.height];
NSData *imgData = UIImageJPEGRepresentation(resizedImg, 0.9);
NSString *stringDataImage = [NSString stringWithFormat:#"%#",imgData];
[dict setObject:stringDataImage for key#"image"];
// POST Request to save the image in DB ...
Now when I try to load the image and set it into my UIImageView I do this way :
NSData *data = [[[MyUser sharedUser] picture] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:data]];
Or
NSData *data = [[[MyUser sharedUser] picture] dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
self.imageView.image = [UIImage withData:data];
But this doesn't work.
data is not equal to imgData, I think it's the encoding but I can find the good one.
And [UIImage withData:data] return nil;
Can you help me?
EDIT :
Convert and save
UIImage *resizedImg = [Generics scaleImage:self.photo.image toResolution:self.photo.frame.size.width and:self.photo.frame.size.height];
NSData *imgData = UIImageJPEGRepresentation(resizedImg, 0.9);
[dict setObject:[imgData base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength] forKey:#"image"];
Load the image
NSData *data = [[NSData alloc] initWithBase64EncodedData:[[MyUser sharedUser] picture] options:kNilOptions];
NSLog(#"%#", data);
self.image.image = [UIImage imageWithData:data];
You are converting the NSData to a string and saving that to your database. Two issues:
Your choice of using the stringWithFormat construct is an inefficient string representation of your data (resulting in string representation that is roughly twice the size). You probably want to use base64 (for which the string representation is only 33% larger).
You are saving your string representation, but never converting it back to binary format after retrieving it. You could write a routine to do this, but it's better to just use established base64 formats.
If you want to save the image as a string in your database, you should use base64. Historically we would have directed you to one of the many third party libraries (see How do I do base64 encoding on iphone-sdk?) for converting from binary data to base64 string (and back), or, iOS 7 now has native base 64 encoding (and exposes the private iOS 4 method, in case you need to support earlier versions of iOS).
Thus to convert NSData to NSString base64 representation:
NSString *string;
if ([data respondsToSelector:#selector(base64EncodedStringWithOptions:)]) {
string = [data base64EncodedStringWithOptions:kNilOptions]; // iOS 7+
} else {
string = [data base64Encoding]; // pre iOS7
}
And to convert base64 string back to NSData:
NSData *data;
if ([NSData instancesRespondToSelector:#selector(initWithBase64EncodedString:options:)]) {
data = [[NSData alloc] initWithBase64EncodedString:string options:kNilOptions]; // iOS 7+
} else {
data = [[NSData alloc] initWithBase64Encoding:string]; // pre iOS7
}
If you really want to turn binary data into a string you should be using base64 encoding. Luckily for you, NSData now supports Base64 natively
So you could get your string from data with:
NSString *stringDataImage = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
And you could turn this back into NSData with:
NSData *imgData = [[NSData alloc] initWithBase64EncodedString:stringDataImage options:kNilOptions];

GDataXML updating xml data

I am trying to update an xml file. After suggestion I ended up choosing GdataXml.
So I am trying to update options.xml file.
Original File
<Dat>
<Name>Tom</Name>
<Option>1</Option>
</Dat>
I need to change "Tom" to "Jim" and save in the same file
Here is the code I tried.
-(void)saveToXML
{
NSString* path = [[NSBundle mainBundle] pathForResource:#"options" ofType:#"xml"];
NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:path];
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
GDataXMLElement *rootElement = [GDataXMLElement elementWithName:#"Dat"];
NSArray *mySettings = [doc.rootElement elementsForName:#"Dat"];
for (GDataXMLElement *mySet in mySettings)
{
NSString *name;
NSArray *names = [mySet elementsForName:#"Name"];
if (names.count > 0)
{
GDataXMLElement *childElement = (GDataXMLElement *) [names objectAtIndex:0];
name = childElement.stringValue;
NSLog(childElement.stringValue);
[childElement setStringValue:#"Jim"];
}
}
[xmlData writeToFile:path atomically:YES];
}
But this is not updating options.xml file. Can some one help on this ?
The missing line of code you are looking for is
NSData *xmlData = doc.XMLData;
from Anupdas answer on your last question. You are currently reading a file into memory, initializing a new object using that memory, updating that new object and then writing the original file's memory into the new file location. So essentially you are reading a file and then writing the same file back to the file location.

How to convert formatted content of NSTextView to string

I need transfer content of NSTextView from Mac app to iOS app. I'm using XML as transfered file format.
So I need to save content of NSTextView (text, fonts, colors atd.) as a string. Is there any way how to do that?
One way to do this is to archive the NSAttributedString value. Outline sample code typed directly into answer:
NSTextView *myTextView;
NSString *myFilename;
...
[NSKeyedarchiver archiveRootObject:myTextStorage.textStorage
toFile:myFilename];
To read it back:
myTextView.textStorage.attributedString = [NSKeyedUnarchiver unarchiveObjectWithFile:myFilename];
That's all that is needed to create and read back a file. There are matching methods which create an NSData rather than a file, and you can convert an NSData into an NSString or just insert one into an NSDictionary and serialise that as a plist (XML), etc.
Your best bet is probably to store the text as RFTD and load it as such in the other text view via an NSAttributedString.
// Load
NSFileWrapper* filewrapper = [[NSFileWrapper alloc] initWithPath: path];
NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithFileWrapper: filewrapper];
NSAttributedString* origFile = [NSAttributedString attributedStringWithAttachment: attachment];
// Save
NSData *data = [origFile RTFDFromRange: NSMakeRange(0, [origFile length]) documentAttributes: nil];
[[NSFileManager defaultManager] createFileAtPath: path contents: data attributes:nil];

Add an NSDictionary to image metadata

I'm trying to save an image with some custom metadata to a Photo Album. The custom metadata I would like to save should be in the form of a NSDictionary. Until now I have only succeeded in inserting an NSArray into the image metadata by using something like below:
NSMutableDictionary *metadata = [[NSMutableDictionary alloc] init];
[metadata setObject:#[#"ele1", #"ele2"] forKey:(NSString*)kCGImagePropertyIPTCKeywords];
NSMutableDictionary *meta = [[NSMutableDictionary alloc] init];
[meta setObject:metadata forKey:(NSString*)kCGImagePropertyIPTCDictionary];
// pass the meta dictionary into writeImageDataToSavedPhotosAlbum
But what I would like is to pass a dictionary into setObject.
Has anyone succeeded in inserting a custom metadata into an image where the metadata is an NSDIctionary?
Additional information
I'm using the code I found here Save CUSTOM metadata in an image taken from AVFoundation in iOS, to add a dictionary to the image metadata but still no luck. The original file is in the temporary directory and the final file is created via writeImageDataToSavedPhotosAlbum. Like in the link, the resulting image doesn't contain the dictionary. Any idea?
CGImageSourceRef source = CGImageSourceCreateWithData((CFMutableDataRef)data, NULL);
NSDictionary *metadata = [(NSDictionary *) CGImageSourceCopyPropertiesAtIndex(source,0,NULL)autorelease];
NSMutableDictionary *metadataAsMutable = [metadata mutableCopy];
NSMutableDictionary *RAWDictionary = [[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyRawDictionary]mutableCopy];
if(!RAWDictionary) {
RAWDictionary = [NSMutableDictionary dictionary];
}
[RAWDictionary setValue:#"value1" forKey:#"key1"];
[RAWDictionary setValue:#"value2" forKey:#"key2"];
[metadataAsMutable setObject:RAWDictionary forKey:(NSString *)kCGImagePropertyRawDictionary];
NSMutableData *newData = [NSMutableData data];
CFStringRef UTI = CGImageSourceGetType(source);
CGImageDestinationRef destination = CGImageDestinationCreateWithData((CFMutableDataRef)newData, UTI, 1, NULL);
if(!destination) {
NSLog(#"***Could not create image destination ***");
}
CGImageDestinationAddImageFromSource(destination,source,0, (CFDictionaryRef)metadataAsMutable);
BOOL success = NO;
success = CGImageDestinationFinalize(destination);
if(!success) {
NSLog(#"***Could not create data from image destination ***");
}
Try this :
//covert image to nsdata format
NSData *imageData = [[NSData alloc]initWithContentsOfFile:#"your image path"];
NSMutableDictionary *metadata = [[NSMutableDictionary alloc] init];
[metadata setObject:imageData forKey:#"imageData"];

Resources