How to Save and Load by iOS Programming - objective-c

I have an application that I want to have take pictures using a UIImagePickerController, then stick said resulting image in a thumbnail view. But, when you exit the app, I want to re-display the same thumbnail as when the user last left off. My question is threefold:
What is the best way to implement saving and loading the image between app life cycles?
How would I go about changing the default shutter sound when the user takes a photo?
How can I reset all of the above to some default setting if the user so chooses?

Trying Using Core Data or NSUserDefault..
Some Links get you Started:
1.http://www.raywenderlich.com/934/core-data-on-ios-5-tutorial-getting-started
2.http://maniacdev.com/2012/03/tutorial-getting-started-with-core-data-in-ios-5-using-xcode-storyboards/
3. Some Code:
//Saving:
[[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(image)forKey:key];
//Loading:
NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:key];
UIImage* image = [UIImage imageWithData:imageData];

what you can do at delegate you just save your image locally(I usually prefer sqlite) and when you start your app you just need to execute a select query to check whether the image exist or not and if it is, then just check which is latest one(or the case which you want to pick up).
Hope, it'll give you working idea.
In any concern, let me informed. :)

Either you save the image data to NSUserDefaults (as metioned by others) or your app's sandbox, or you might as well save the image to the device's camera roll in the didFinishPickingMediaWithInfo delegate like so:
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
//Block Request to save the image to camera roll
[library writeImageToSavedPhotosAlbum:[[info objectForKey:UIImagePickerControllerOriginalImage] CGImage] orientation:(ALAssetOrientation)[[info objectForKey:UIImagePickerControllerOriginalImage] imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
NSLog(#"Error saving to Albums");
} else {
NSLog(#"Saved Image Url %#", assetURL);
}
}];
[library release];
The delegate - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info info dictionary object then has the image url for the key UIImagePickerControllerReferenceURL which you can then use to fetch the image, again using ALAssetsLibrary. HTH.

Related

Rotate image in IKImageBrowserView. Cocoa/Objective C

Im looking for your help, with Cocoa IKImageBrowserView.
I have that browser, and images inside that. The images are taken from the folder that I do provide to it. Kinda like that:
[importedImages removeAllObjects];
[images removeAllObjects];
NSArray *onlyPNGs = [self getAllPngsInLibraryFolder];
NSString *imagesPath = [[FileHelperManager defaultManager] getPathToImagesFolder];
for(NSString *str in onlyPNGs)
{
NSString *mergedPath = [imagesPath stringByAppendingString:str];
[self addAnImageWithPath:mergedPath];
}
[self updateDatasource];
When I do chose particular image from ImageBrowser, I show it in NSImageView, and provide an ability to modify some parameters of this image in database where I do store information about all of them.
The problem what I have met is - I want to support the rotation change of chosen image. I can rotate without any problem an NSImageView preview of selected image, but how can I rotate then this image inside ImageBrowser?
Would be good if somebody can help me with that.
Here is an illustration of what I do try to achieve.
So, steps 1,2 are ok, but how can I do step 3?

how to load image from server (url) to uitableview in Xcode

I need to load image from server(url) to UITableView. So i tired below code, but no use.
UIImageView *img=[[UIImageView alloc]init];
img.frame=fr;
img.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:countimg]]];
[cell.contentView addSubview:img];
Here countimg is NSMutableArray. countimg contains url of all images to load. But its not working, because its not a string variable. I don't know how to change NSMutuableArray to String.
Anyone help me.
You can get string urls from countimg array like this,
[countimg objectAtIndex:index];
Where index is an integer of range between >=0 && < [countimg count]
Now if you're using countimg array in UITableView delegate then, you've replace index variable with indexPath.row.
So for now your code would look like this,
UIImageView *img=[[UIImageView alloc]init];
img.frame=fr;
img.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[countimg objectAtIndex:indexPath.row]]]]; //note this
[cell.contentView addSubview:img];
Update:
As #DavidAtkinson, suggestion, you should not use dataWithContentsOfURL method to load a NSURL to download a image. As its perform in main thread and will stuck the UI until download would not completes. Its better to load image in background.
Also, there's some asynchronous UIImageView's available, one which I am using is SDWebImage.
Use SDWebImage to load your image from server. here using this library you can put placeholder image in tableview cell's image view till the image loaded. You can even cache your image by just doing a single line code
[UIImageView setImageWithUrl:[pass your URL here] placeholderImage:[pass name of placeholder image] options:SDWebImageRefreshCached]
If you are trying to load your images from URL into a tableview,the SDWebImage code from Github does not specify how to do that.You have to create an object at index,then load the object for key name from the file you are parsing from.This will require you to change the SDWebImage code so that instead of parsing directly from a specific url,its parsing from
an object key name that contains an image url from your json or xml file.
Here is a sample code for loading an image from an object key in a json:
NSURL* url = [NSURL URLWithString:[dictionaryObject valueForKey:#"yourfile"]];
NSData *data = [NSData dataWithContentsOfURL:url];
dispatch_sync(dispatch_get_main_queue(), ^{
UIImageView *imgViewThumb=[[UIImageView alloc]initWithFrame:imgView.frame];
[imgViewThumb setImage:[UIImage imageWithData:data]];
[cell addSubview:imgViewThumb];

iOS use cached image with SDWebImage properly

I am using SDWebImage to get pictures.
let's say I have two view controllers A and B. B is the next view of A. they need to show the same image:
[iconIamgeView setImageWithURL:[NSURL URLWithString:#"http://www.example.com/icon.jpg"];
I thought SDWebImage would cache http://www.example.com/icon.jpg after this code in A, so B was going to use the cache. Thus there should not be a detectable latency when I used this code to show the same image in B. However, it seems that I was wrong. there was an obvious latency when I wanted to show this image in B.
How can I use the cache properly? thanks!
I am sorry that the problem I mentioned in the question was not the real problem.
[iconIamgeView setImageWithURL:[NSURL URLWithString:#"http://www.example.com/icon.jpg"];
this code does the cache work well.
the real problem is my code of setting image was not on the main thread, so I could not show the image immediately. I used dispatch_async to solve the problem:
dispatch_async(dispatch_get_main_queue(), ^{
[iconIamgeView setImageWithURL:[NSURLURLWithString:#"http://www.example.com/icon.jpg"];
});
hope this answer may help someone who faces the same issue.
NSURL *imageURL = [NSURL URLWithString:[linkImageArray objectAtIndex:index]];
UIImage *placeholderImage = [UIImage imageNamed : [linkImageArray objectAtIndex: index]];
[imageView setImageWithURL:imageURL
placeholderImage:placeholderImage
options:SDWebImageRefreshCached
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
{
NSLog(#"image loaded");
}];

Cache NSData(with UIImages)

Currently, I'm working on the client for the website. I have tonne of images that I need to load to my TableView. Here is what I'm currectly doing:
NSDictionary *propertyItems = [self.items objectAtIndex:indexPath.row];
cell.fio.font = [UIFont boldSystemFontOfSize:17.0f];
if([propertyItems objectForKey:#"online"] == [NSNumber numberWithInt:1])
cell.fio.textColor = [UIColor colorWithRed:0.3 green:0.6 blue:0.3 alpha:1.0];
dispatch_queue_t downloadPhotosQueue = dispatch_queue_create("downloadPhotosQeue", NULL);
dispatch_async(downloadPhotosQueue, ^{
NSData *photosData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.example.com/%#", [propertyItems objectForKey:#"photo_trumb"]]]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.pic.image = [UIImage imageWithData:photosData];
});
});
cell.fio.text = [propertyItems objectForKey:#"fio"];
I'm doing this in cellForRowAtIndexPath: method.
Everything is loading fast. But the problem is, when I'm scrolling my table down, and after again up, the images are reloading over and over again.
Question: Is there any way to easily cache my UIImages that I'm getting from the server? So if they are loaded once, they wouldn't reload over and over again, while I'm running the app. Maybe I'm doing something wrong?
Thanks in advance!
I strongly recommend AsyncImageView. I use it and it works like a charm. Just set the image url and it handles everything itself.
AsyncImageView *imageView = [[AsyncImageView alloc]init];
imageView.imageURL = [NSURL URLWithString:#"https://www.google.es/logos/classicplus.png"];
It caches the image in memory so it won't retrieve it from the server again. It will also release them when receiving a memory warning.
To load image from a website I use AFNetworking. It provides a class to load an image from an URL:
Start by adding #import "UIImageView+AFNetworking" to the top of a
controller or a view implementation file. This category adds methods
to UIImageView, like:
[imageView setImageWithURL:[NSURL URLWithString:#"…"]];
i recommend this library to accomplish what you want.
in cellForRowAtIndexPath:
[cell.imageView setImageWithURL:
[NSURL URLWithString:[NSString stringWithString:#"www.yourimagepath.path"]]
placeholderImage:[UIImage imageNamed:#"no_image.jpg"]];
the library will cache the image for you. you can also set the setHolder of the image, so it wont look like a blank image while the images are downloading.
The problem is here :
NSData *photosData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.example.com/%#", [propertyItems objectForKey:#"photo_trumb"]]]];
dataWithContentsOfURL
It launch a request to the Url everytime the function is called (everytime you scrolled).
You need to load all the picture before cellForRowAtIndexPath.
Like in ViewDidLoad.
You can just store them in an array and display your picture's array in cellForRowAtIndexPath.
If it's really fast to load like you say : jsut load picture Once in CellForRowAtIndexPath. Store them in a mutableArray. And check if the picture already exist .

Set activity indicator until image is loaded from server?

I'm new to iOS development so please bear with me.
I'm making a photo-grid using a table view and scroll view.
My question is how could I load an activity indicator until an image downloads from a server and then display the image and remove the activity indicator?
I'm trying to stay away from third-party library's as I want to understand how it works.
Place an Activity Indicator (via Interface Builder or manually) on your view. Set the property to "hide when not animating".
When doing server call, call [activityIndicator startAnimating] (IBOutlet property).
When returning with actual image, call [activityIndicator stopAnimating]. When stopping, it wil automatically hide.
You can also use the activity indicator in the iPhon/Pad status bar. To do this, use [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
Set to NO for hiding it ... (obviously)
Take a look at dowloading an image async for a sample of dl'ing an image.
You would stop the activity indicator in the didReceiveData function.
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCsQFjAA&url=https%3A%2F%2Fgithub.com%2Fjakemarsh%2FJMImageCache&ei=UEp7U_W2GoWB8gWShIGgBQ&usg=AFQjCNEc0a59K2wEOlZ2IbapWhVc87kHmg&bvm=bv.67229260,d.dGc
here you could find JMImage cache files that you could use for downloading images.
You have to change UIImageView+JMImageCache.m file
if(i) {
dispatch_async(dispatch_get_main_queue(), ^{
safeSelf.jm_imageURL = nil;
safeSelf.image = i;
[safeSelf setNeedsLayout];
[safeSelf setNeedsDisplay];
if (completionBlock) {
completionBlock(i).
}
});
then use method
enter code here
{
[yourImageView setImageWithURL:[NSURL URLWithString:urlString] placeholder:[UIImage imageNamed:#"placeholder"] completionBlock:^(UIImage *image)
{
// remove added activity indicator here
}failureBlock:^(NSURLRequest *req,NSURLResponse *resp,NSError *error)
{
// show error message
}];
}