writeToFile not properly saving data - objective-c

I have data from a url (.m4a) and I am trying to save the file so I can edit it's metadata (change background image). The code below doesn't seem to work and I have no idea why. It is saving a file, but the file is empty.
_previewData = [NSMutableData dataWithContentsOfURL:[NSURL URLWithString:#"http://a281.phobos.apple.com/us/r1000/119/Music/v4/f1/7b/d6/f17bd6e3-55c0-b7e0-9863-bc522900e950/mzaf_5153970109972844579.aac.m4a"]];
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString *path = [documentDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"file.mp4"]];
NSFileManager *filemanager;
filemanager = [NSFileManager defaultManager];
[_previewData writeToFile:path atomically:YES];
if ([filemanager fileExistsAtPath:path]) {
// Runs
NSLog(#"It worked");
}
NSLog(#"%#",path);
ANMovie* file = [[ANMovie alloc] initWithFile:path]; // or .mp4
NSData* jpegCover = UIImageJPEGRepresentation(artworkImage, 1.0);
_imageView.image = [UIImage imageWithData:jpegCover];
ANMetadata* metadata = [[ANMetadata alloc] init];
metadata.albumCover = [[ANMetadataImage alloc] initWithImageData:jpegCover type:ANMetadataImageTypeJPG];
[file setMovieMetadata:metadata];
[file close];
_previewData = [NSMutableData dataWithContentsOfFile:path];
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
NSDictionary *imageItem=#{#"public.mpeg-4-audio":self.previewData};
NSDictionary *textItem=#{#"public.plain-text":self.linkData};
pasteboard.items=#[imageItem,textItem];

Related

Getting Error in Share to Instagram iOS Objective C

I want to share a single image to Instagram "image.png" Is this an iOS 11 error?
I'm getting this error:
Couldn't get file size for file:/var/mobile/Containers/Data/Application/492BF71E-E579-4792-8BE9-144D9C1EC73D/Documents/insta.igo -- file:///: Error Domain=NSCocoaErrorDomain Code=260 "The file “insta.igo” couldn’t be opened because there is no such file." UserInfo={NSURL=file:/var/mobile/Containers/Data/Application/492BF71E-E579-4792-8BE9-144D9C1EC73D/Documents/insta.igo -- file:///, NSFilePath=/file:/var/mobile/Containers/Data/Application/492BF71E-E579-4792-8BE9-144D9C1EC73D/Documents/insta.igo, NSUnderlyingError=0x1cc054760 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
Here's the code
-(void)shareInInstagram{
UIImage *imge = [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(imge); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"insta.igo"]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
NSLog(#"image saved");
CGRect rect = CGRectMake(0 , 0, 0, 0);
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIGraphicsEndImageContext();
NSString *fileNameToSave = [NSString stringWithFormat:#"Documents/insta.igo"];
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:fileNameToSave];
NSLog(#"jpg path %#",jpgPath);
NSString *newJpgPath = [NSString stringWithFormat:#"file://%#",jpgPath]; //[[NSString alloc] initWithFormat:#"file://%#", jpgPath] ];
NSLog(#"with File path %#",newJpgPath);
NSURL *igImageHookFile = [[NSURL alloc] initFileURLWithPath:newJpgPath];
NSLog(#"url Path %#",igImageHookFile);
self.dic.UTI = #"com.instagram.exclusivegram";
self.dic = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
self.dic=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
[self.dic presentOpenInMenuFromRect:rect inView:self.view animated:YES];
}
This code works in my app.
GRect rect = CGRectMake(0 ,0 , 0, 0);
UIImage *image = [self getImageToShare];
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *jpgPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"insta.igo"]]; //add our image to the path
[fileManager createFileAtPath:jpgPath contents:imageData attributes:nil]; //finally save the path (image)
NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:#"file://%#", jpgPath]];
self.documentController.UTI = #"com.instagram.exclusivegram";
self.documentController = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
self.documentController=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
[self.documentController presentOpenInMenuFromRect:rect inView: self.view animated: YES ];
NSURL *instagramURL = [NSURL URLWithString:#"instagram://media?id=MEDIA_ID"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
[self.documentController presentOpenInMenuFromRect:rect inView:self.view animated:YES ];
}else{
[self showMessage:#"No Instagram Found"];
}

How do I generate thumbnail of map using given Lat/Long in iOS?

I am working on a chat application where I am going to send a map to another user.
Below is my code to generate a thumbnail of a map. Is there any way to generate a map thumbnail in Objective-C?
Code to generate thumbnail of static map:
NSString *staticMapUrl = [NSString stringWithFormat:#"http://maps.google.com/maps/api/staticmap?markers=color:blue|%#,%#&%#&sensor=true",_lat, _longi,#"zoom=13&size=%dx%d"];
NSURL *mapUrl = [NSURL URLWithString:[staticMapUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
UIImage *Mapimage = [UIImage imageWithData: [NSData dataWithContentsOfURL:mapUrl]];
Save thumbnail images in document directories:
NSString *datapathMap=[Locations stringByAppendingPathComponent:[NSString stringWithFormat:#"Sm_%#_lc_%#.jpg",userid,dateString1]];
NSData *urlData = [NSData dataWithContentsOfURL:mapUrl];
datapathMap = [datapathMap stringByStandardizingPath];
[urlData writeToFile:datapathMap atomically:YES];
Send thumbnail data to bubble to display thumbnail:
NSBubbleData *MapSendBubble = [NSBubbleData dataWithImage:mapImage date:[NSDate date] type:BubbleTypeMine];
MapSendBubble.avatar = [UIImage imageNamed:#"avatar1.png"];
[bubbleData addObject:MapSendBubble];
[_bubbleTable reloadData];
Send map:
NSDate *today=[NSDate date];
NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
[dateFormat1 setDateFormat:#"YYYYMMddhhmmss"];
NSString *dateString1=[dateFormat1 stringFromDate:today];
NSString *userid= #"mc1"; NSString *latlong=[NSString stringWithFormat:#"%#%#",[_lat substringToIndex:2],[_longi substringToIndex:2]];
[map setTag:[[NSString stringWithFormat:#"%#",latlong] integerValue]];
NSString *longlat=[NSString stringWithFormat:#"%#,%#",_longi,_lat];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MMM-yy HH:mm:ss"];
NSString *date=[dateFormat stringFromDate:[NSDate date]];
//Find a cache directory. You could consider using documents dir instead (depends on the data you are fetching)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSError *error;
NSString *MainFolder = [path stringByAppendingPathComponent:[NSString stringWithFormat:#"/SmoothChat"]];
NSString *Locations=[MainFolder stringByAppendingPathComponent:[NSString stringWithFormat:#"/Locations"]];
if (![[NSFileManager defaultManager] fileExistsAtPath:MainFolder])
{
[[NSFileManager defaultManager] createDirectoryAtPath:MainFolder withIntermediateDirectories:NO attributes:nil error:&error];
}
if (![[NSFileManager defaultManager] fileExistsAtPath:Locations])
{
[[NSFileManager defaultManager] createDirectoryAtPath:Locations withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *staticMapUrl = [NSString stringWithFormat:#"http://maps.google.com/maps/api/staticmap?markers=color:red|%#,%#&%#&sensor=true",_lat,_longi,#"zoom=15&size=300x180"];
NSURL *mapUrl = [NSURL URLWithString:[staticMapUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
UIImage *Mapimage = [UIImage imageWithData: [NSData dataWithContentsOfURL:mapUrl]];
NSString *datapathMap=[Locations stringByAppendingPathComponent:[NSString stringWithFormat:#"Sm_%#_lc_%#.jpg",userid,dateString1]];
NSData *urlData = [NSData dataWithContentsOfURL:mapUrl];
datapathMap = [datapathMap stringByStandardizingPath];
[urlData writeToFile:datapathMap atomically:YES];
// NSString *uuid1 = [[NSUUID UUID] UUIDString];
// [self sendXMPPMessage:1 :[NSString stringWithFormat:#"lc%#",value] :[NSString stringWithFormat:#"oi_%#_lc_%#.jpg",userid,dateString1] :#"" :jsonstring :[NSString stringWithFormat:#"%#",longlat] :_user :#"" :#"" :#"" :[[NSUserDefaults standardUserDefaults] stringForKey:#"current_chat"] :#"" :#"" :_senderType :[self currentDateTme] :0];
NSBubbleData *photoBubble11 = [NSBubbleData dataWithImage:staticMapUrl date:[NSDate date] type:BubbleTypeMine];
photoBubble11.avatar = [UIImage imageNamed:#"avatar1.png"];
[bubbleData addObject:photoBubble11];
[_bubbleTable reloadData];
[self goToBottom];
[map setHidden:YES];
[blurView setHidden:YES];
[_NewView setHidden:YES];
[map removeAnnotation:point];
currentLocation=nil;
[locationManager stopUpdatingLocation];

How do I download an image from a URL and save it to my computer?

How would I download an image from a URL, and have that saved to the computer using Objective-C? This is what I got so far:
NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage *imageFromURL = [self getImageFromURL:#"https://www.google.com/images/srpr/logo11w.png"];
[self saveImage:imageFromURL withFileName:#"Google Logo" ofType:#"png" inDirectory:documentsDirectoryPath];
UIImage *imageFromWeb = [self loadImage:#"Google Logo" ofType:#"png" inDirectory:documentsDirectoryPath];
Xcode complains about UIIMage, trying to replace with NSImage. It also complains about an undeclared identifier 'self'.
I need to make an HTTP call to perform this as well. Explain this to me like I'm 5.
Here is the code to Save the image into document Directory.
-(void)saveImagesInLocalDirectory
{
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imgName = #"image.png";
NSString *imgURL = #"www.example.com/image/image.png";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *writablePath = [documentsDirectoryPath stringByAppendingPathComponent:imgName];
if(![fileManager fileExistsAtPath:writablePath]){
// file doesn't exist
NSLog(#"file doesn't exist");
if (imgName) {
//save Image From URL
[self getImageFromURLAndSaveItToLocalData:imgName fileURL:imgURL inDirectory:documentsDirectoryPath];
}
}
else{
// file exist
NSLog(#"file exist");
}
}
-(void) getImageFromURLAndSaveItToLocalData:(NSString *)imageName fileURL:(NSString *)fileURL inDirectory:(NSString *)directoryPath {
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
NSError *error = nil;
[data writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", imageName]] options:NSAtomicWrite error:&error];
if (error) {
NSLog(#"Error Writing File : %#",error);
}else{
NSLog(#"Image %# Saved SuccessFully",imageName);
}
}
And this is the one method code..
-(void)saveImagesInLocalDirectory
{
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imgName = #"image.png";
NSString *imgURL = #"www.example.com/image/image.png";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *writablePath = [documentsDirectoryPath stringByAppendingPathComponent:imgName];
if(![fileManager fileExistsAtPath:writablePath]){
// file doesn't exist
NSLog(#"file doesn't exist");
//save Image From URL
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]];
NSError *error = nil;
[data writeToFile:[documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", imgName]] options:NSAtomicWrite error:&error];
if (error) {
NSLog(#"Error Writing File : %#",error);
}else{
NSLog(#"Image %# Saved SuccessFully",imgName);
}
}
else{
// file exist
NSLog(#"file exist");
}
}
This is my solution!
+(BOOL)downloadMedia :(NSString*)url_ :(NSString*)name{
NSString *stringURL = url_;
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,name];
[urlData writeToFile:filePath atomically:YES];
return YES;
}
return NO;
}
+(UIImage*)loadMedia :(NSString*)name{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:name];
UIImage *img_ = [UIImage imageWithContentsOfFile:getImagePath];
return img_;
}

Saving images to a directory

Hi I want to save an image to a directory, I pass the NSData and do what I think will save the file in a directory I create but the problem is that it doesn't save. This is what I have so far. Why doesn't the initWithContentsOfURL:encoding:error: work, it returns null but the other method I used works? The main problem is WRITETOURL which returns a 0 which i think means that the information wasn't stored properly, any tips?
NSFileManager *fm = [[NSFileManager alloc] init];
NSArray * directoryPaths = [fm URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSLog(#"%#", directoryPaths);
NSURL* dirPath = nil;
dirPath = [[directoryPaths objectAtIndex:0] URLByAppendingPathComponent:[NSString stringWithFormat:#"photos.jpeg"]];
NSError* theError = nil;
[fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&theError];
UIImage* photoToStore = [UIImage imageWithData:photoToSave];
NSString *pathContainingPhoto = [[NSString alloc] initWithFormat:#"%#.jpeg", UIImageJPEGRepresentation(photoToStore, 1.0)];
NSError *error = nil;
BOOL OK = [pathContainingPhoto writeToURL:dirPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"OK = %d", OK); //Returns 0
NSLog(#"%#", dirPath);
//WHY DOESNT THIS VERSION WORK?
// NSString *pathToFile = [[NSString alloc] initWithContentsOfURL:dirPath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", pathToFile);
NSString* pathToFile = [NSString stringWithContentsOfURL:dirPath encoding:nil error:nil];
NSArray *dirContents = [fm contentsOfDirectoryAtPath:pathToFile error:nil];
NSLog(#"%#", dirContents);
Do like this and int count in .h file and set its intial value count = 0; in viewDidLoad:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:[NSString stringWithFormat:#"Image_%d.png",count];
error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath]) // removing item it already exuts
{
[[NSFileManager defaultManager] removeItemAtPath:stringPath error:&error];
}
if(photoToSave) // nsdata of image that u have
{
[photoToSave writeToFile:stringPath atomically:YES];
}
count++; // maintaining count of images

Merge audio and video/image to create a movie file

I want to merge an Audion CAF file and a video/image UIImage to create a movie file (in .mov format).
Say that my audio is 30 seconds long and I have a UIImage; I want to create a .mov file such that the UIImage is displayed the entire time the audio is playing.
I found this reference:
How to add audio to video file on iphone SDK
Can anyone tell me, is it helpful in my case, since the length of my audio and image/video is different?
Thanks in advance.
Yes, you should use AVMutableComposition. To create the video track from your UIImage use AVAssetWriter.
Quicktime Pro can do this. Done that for my own app.
You create the movie from the images. Quicktime offers to read a sequence of images and creates a movie from it. He ask for the FPS during import as well.
The audio track can then simply merged, pasted somewhere or scaled to a selected range of the movie.
use this i found this somewhere in net, i don't remember,....
NSString *fileNamePath = #"audio.caf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *oldappSettingsPath = [documentsDirectory stringByAppendingPathComponent:fileNamePath];
NSURL *audioUrl = [NSURL fileURLWithPath:oldappSettingsPath];
NSString *fileNamePath1 = #"output.mp4";
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths1 objectAtIndex:0];
NSString *oldappSettingsPath1 = [documentsDirectory1 stringByAppendingPathComponent:fileNamePath1];
NSLog(#"oldpath=%#",oldappSettingsPath);
NSURL *videoUrl = [NSURL fileURLWithPath:oldappSettingsPath1];
if (avPlayer.duration >0.00000)
{
NSLog(#"SOMEDATA IS THERE ");
AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:audioUrl options:nil];
AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:videoUrl options:nil];
AVMutableComposition* mixComposition = [AVMutableComposition composition];
NSLog(#"audio =%#",audioAsset);
AVMutableCompositionTrack *compositionCommentaryTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionCommentaryTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration) ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];
AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:kCMTimeZero error:nil];
AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetPassthrough];
NSString* videoName = #"export.mov";
NSString *exportPath = [NSTemporaryDirectory() stringByAppendingPathComponent:videoName];
NSURL *exportUrl = [NSURL fileURLWithPath:exportPath];
if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath])
{
[[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
}
_assetExport.outputFileType = #"com.apple.quicktime-movie";
NSLog(#"file type %#",_assetExport.outputFileType);
_assetExport.outputURL = exportUrl;
_assetExport.shouldOptimizeForNetworkUse = YES;
[_assetExport exportAsynchronouslyWithCompletionHandler:
^(void )
{
NSString *fileNamePath = #"sound_record.mov";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *oldappSettingsPath = [documentsDirectory stringByAppendingPathComponent:fileNamePath];
// if ([[NSFileManager defaultManager] fileExistsAtPath:oldappSettingsPath]) {
//
// NSFileManager *fileManager = [NSFileManager defaultManager];
// [fileManager removeItemAtPath: oldappSettingsPath error:NULL];
//
// }
NSURL *documentDirectoryURL = [NSURL fileURLWithPath:oldappSettingsPath];
[[NSFileManager defaultManager] copyItemAtURL:exportUrl toURL:documentDirectoryURL error:nil];
[audioAsset release];
[videoAsset release];
[_assetExport release];
}
];