In my app I need to search images from google images for a particular word.
for example, i want to search image for Earth
.
How to search images from Google Images and save selected images in documents directory?
Is there any API that can I use? Or any other way to do it?
Google Image Search API / JSON Developer's Guide.
You will have to display the images yourself as the result is a json response. However this will give you maximum control. The result will contain a thumbnail URL which you can use to show the preview.
Downloading images can be done in many ways:
The use of the Google API does only work under certain circumstances such as
"Applications that use this interface must abide by all existing Terms of Service. Most importantly, you must correctly identify yourself in your requests."
After receiving the results you can save the image to disk with:
NSString *aFileName = @"myImage.jpg";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *path = [documentDirectory stringByAppendingPathComponent:aFileName];
[myImageAsData writeToFile:path atomically:YES];
alternatively if you've got the image as UIImage already:
NSData *myImageAsData = [NSData dataWithData:UIImagePNGRepresentation(anImage)];
[myImageAsData writeToFile:path atomically:YES];
First, you want the Google Image Search API. http://code.google.com/apis/imagesearch/
Next, if you're cool with only targeting iOS 4.0 and later, you can use Grand Central Dispatch and the very useful sycnhronous data APIs included in iOS. Specifically, I'm thinking of [NSData dataWithContentsOfURL:]. This will block the thread until it downloads the whole image, so don't run it on the main thread. Fortunately, GCD lets you throw stuff on a background thread with ease. So your code will probably look something like this:
dispatch_queue_t NetworkQueue = dispatch_queue_create("NetworkQueue", 0);
dispatch_async(NetworkQueue,^{
NSData* imageResultsData = [NSData dataWithContentsOfURL:
[NSURL urlWithString:@"https://ajax.googleapis.com/ajax/services/search/images?some_images_query_here"];
//do something with that data
//let's say you unpacked it into an NSArray of NSURLs
for(NSURL* url in myImageArray) {
dispatch_async(NetworkQueue,^{
NSData* imageData = [NSData dataWithContentsOfURL:url];
[imageData writeToFile:file_name_here atomically:YES];
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With