Not able to display images from particular directory IOS - objective-c

I'm trying to create image from this location :
NSString *documentsCacheDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *fileName = #"image1.jpg";
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsCacheDirectory, fileName];
So applying to my Image :
UIImage *myImage = [UIImage imageNamed:filePath];
..setting this image as background to my button etc. etc.
But I'm not seeing any images displayed. However when I use the same technique for reading a file :
NSString *documentsCacheDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *fileName = #"file.txt";
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsCacheDirectory, fileName];
NSString *fileContents = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
for (NSString *line in [cacheFileContents componentsSeparatedByString:#"\n"]) {
.....
}
Reading file works just fine, but image does not, any reasons why?

imageNamed: is for images that are bundled with your app, you don't use this with a path. Use imageWithContentsOfFile: instead.

Related

writeToFile not properly saving data

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];

How to save data locally in app? [duplicate]

This question already has answers here:
Working with data in iOS Apps (What to choose? NSData, CoreData, sqlite, PList, NSUserDefaults)
(2 answers)
Closed 9 years ago.
I've been struggling with this for ages now and I really need some good help here. :)
I have an app where I'm parsing a quite big JSON into appdelegate's didFinishLaunchingWithOptions.
My Model Objects are:
Tab:
NSString *title
NSMutableArray *categories
Category:
NSString *title
NSMutableArray *items
Item
NSString *title
NSString *description
UIImage *image
I need to save the data locally, cause the parsing takes about 15 seconds every time my app starts. I'm using the SBJSON framework.
Here's my code for parsing:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"json_template" ofType:#"json"];
NSString *contents = [NSString stringWithContentsOfFile: filePath encoding: NSUTF8StringEncoding error: nil];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSMutableDictionary *json = [jsonParser objectWithString: contents];
tabs = [[NSMutableArray alloc] init];
jsonParser = nil;
for (NSString *tab in json)
{
Tab *tabObj = [[Tab alloc] init];
tabObj.title = tab;
NSDictionary *categoryDict = [[json valueForKey: tabObj.title] objectAtIndex: 0];
for (NSString *key in categoryDict)
{
Category *catObj = [[Category alloc] init];
catObj.name = key;
NSArray *items = [categoryDict objectForKey:key];
for (NSDictionary *dict in items)
{
Item *item = [[Item alloc] init];
item.title = [dict objectForKey: #"title"];
item.desc = [dict objectForKey: #"description"];
item.url = [dict objectForKey: #"url"];
if([dict objectForKey: #"image"] != [NSNull null])
{
NSURL *imgUrl = [NSURL URLWithString: [dict objectForKey: #"image"]];
NSData *imageData = [NSData dataWithContentsOfURL: imgUrl];
item.image = [UIImage imageWithData: imageData];
}
else
{
UIImage *image = [UIImage imageNamed: #"standard.png"];
item.image = image;
}
[catObj.items addObject: item];
}
[tabObj.categories addObject: catObj];
}
[tabs addObject: tabObj];
}
What is the best way of doing this? Using Core Data or NSFileManager?
If you have som code example too it will make me very happy.
This is the last thing i need to fix before the app is ready for app store and it just kills me! I can't solve this problem.
If you are working on iOS then you save a file to the Documents folder. On Mac OS X it would be in the Application Support folder. Since you are on iOS, read this answer for how to access the Documents folder.
All of the objects that you want to store should implement NSCoding. The above variables already do. Should you want to store the tabs, categories and items directly they would need to implement NSCoding. Then all you need is to serialize them to a file. When opening you app you can look for this file and get your objects back without parsing.
The code should look something like this (untested and error checking is ommited for brevity):
- (void) saveStateToDocumentNamed:(NSString*)docName
{
NSError *error;
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths[0] stringByAppendingPathComponent:docName];
if ([fileMan fileExistsAtPath:docPath])
[fileMan removeItemAtPath:docPath error:&error];
// Create the dictionary with all the stuff you want to store locally
NSDictionary *state = #{ ... };
// There are many ways to write the state to a file. This is the simplest
// but lacks error checking and recovery options.
[NSKeyedArchiver archiveRootObject:state toFile:docPath];
}
- (NSDictionary*) stateFromDocumentNamed:(NSString*)docName
{
NSError *error;
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths[0] stringByAppendingPathComponent:docName];
if ([fileMan fileExistsAtPath:docPath])
return [NSKeyedUnarchiver unarchiveObjectWithFile:docPath];
return nil;
}

Is it possible for UIActivityViewController to attach AAC?

I tried this with no luck:
NSData *imageData = UIImageJPEGRepresentation([sight.photo valueForKey:#"image"], 0.8);
NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docsPath stringByAppendingPathComponent:#"sound.m4a"];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
NSData *aacData = [sight.sound valueForKey:#"soundrecord"];
[aacData writeToURL:fileUrl atomically:YES];
// NSString *text = self.textField.text;
NSArray *items = #[imageData, aacData];
Yes, but you need to pass the audio file URL to the activity sheet rather than the NSData.
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *filePath = [docPath stringByAppendingPathComponent:#"sound.aac"];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath isDirectory:NO];
NSArray *activityItems = #[fileUrl];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
[self presentViewController:activityVC animated:YES completion:nil];
If you find that the attachment doesn't appear when launching the email composer from the activity sheet, make sure your file path and URL are correct and that the file exists (including the extension on the device/simulator drive).
To open a file on the simulator, go to folder (~/Library/Application Support/iPhone Simulator/...
To check the file name on device, go to XCode Organizer Window and select the Applications tab within the debugging device connected. You should see the file structure on the main panel.

write NSString to file

I'm trying to write a string to a file and store that in the applicationSupport folder within my app. But my NSLog() statement doesn't log anything in the debugger. I have tried to go through it with the debugger, and i can see that the content is nil, so i'm guessing that's why it's not outputting anything, but i don't know why it's set to nil. Can anybody see my mistake?
NSString *document = [[[[[[[[description stringByAppendingString:#" "]stringByAppendingString:focus]stringByAppendingString:#" "]stringByAppendingString:level]stringByAppendingString:#" "]stringByAppendingString:equipment]stringByAppendingString:#" "]stringByAppendingString:waterDepth];
//NSLog(#"%#", document);
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *supportDirectory = [paths objectAtIndex:0];
//filename
NSString *filename = [NSString stringWithFormat:[_nameTextField.text stringByAppendingString:#".txt"], supportDirectory];
[document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:nil];
NSLog(#"%#", content);
filename is wrong. It should have the following format: "directory/file.extension". You can use the methods stringByAppendingPathComponent and stringByAppendingPathExtension to construct such a string.
NSString *filename = [supportDirectory stringByAppendingPathComponent:[_nameTextField.text stringByAppendingPathExtension:#"txt"]];
Also, as a side note, the first line should be rewritten using stringWithFormat like this:
NSString *document = [NSString stringWithFormat:#"%# %# %# %# %#", description, focus, level, equipment, waterDepth];
You have wrong initialize filename. It should be:
NSString *filename = [NSString stringWithFormat:#"%#/%#", supportDirectory,[_nameTextField.text stringByAppendingString:#".txt"]];
it will works! Good luck:)
The
NSString *filename = [NSString stringWithFormat:[_nameTextField.text stringByAppendingString:#".txt"], supportDirectory];
is wrong. It should be:
NSString *filename = [NSString stringWithFormat:"%#%#",[_nameTextField.text stringByAppendingString:#".txt"], supportDirectory];

How to upload image, which is not saved on the device to the dropbox account?(IOS)

Dropbox restClient saves only files. So i want to save the image in local folder first and then to upload it, as a result it saves file, but it is corrupted.
NSString *localPath = [[NSBundle mainBundle] pathForResource:#"Info" ofType:#"plist"];
NSString *jpegFilePath = [NSString stringWithFormat:#"%#/test.jpeg",localPath];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[data2 writeToFile:jpegFilePath atomically:YES];
NSString *filename = #"test.jpeg";
NSString *destDir = #"/";
[[self restClient] uploadFile:filename toPath:destDir
withParentRev:nil fromPath:localPath];
I am an idiot, solved
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingString:#"test.jpg"];
NSData * data = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[data writeToFile:path atomically:YES];
[self.restClient uploadFile:#"test.jpg" toPath:#"/" withParentRev:nil fromPath:path];
you will have to call DBRestClient methods from the main thread or a thread that has a run loop. Otherwise the delegate methods will not be called.
what you will have to do is first alloc init yoir DBRestClient object then make it's delegate self and then you can easily upload your file.below is an example
NSString *destDir = #"/";
restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
restClient.delegate = self;
[restClient uploadFile:yourfilename toPath:destDir withParentRev:nil fromPath:sourcepath];
Happy Coding!!!!!!
You can't save into the bundle. You should use documents or cache folder:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];