Google Image Search iPhone URL Data - iphone

I want to do a simple google image search and return one image for whatever is string I'm searching for. image is null when I finish, what am I doing wrong? Code below:
-(void)getGoogleImage
{
NSString *google = [NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults]objectForKey:#"string"]];
NSString *newGoogle = [google stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *fullGoogle = [NSString stringWithFormat:#"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%#",newGoogle];
NSURL * url = [NSURL URLWithString:fullGoogle];
NSURLRequest * request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Did Recieve Response");
responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
NSLog(#"Did Recieve Data");
[responseData appendData:data];
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
NSLog(#"Did Fail");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Did Finish");
image = [[UIImage alloc]initWithData:responseData];
}
When i search for dog i get this in a web browser:
{"responseData": {"results":[{"GsearchResultClass":"GimageSearch","width":"220","height":"211","imageId":"ANd9GcTZKvO0mDGuDdifdhW3TEG8bmcPM23DMGEB4wevzBuIPp7HMMwQ3dTetVc","tbWidth":"107","tbHeight":"103","unescapedUrl":"http://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Timba%2B1.jpg/220px-Timba%2B1.jpg","url":"http://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Timba%252B1.jpg/220px-Timba%252B1.jpg","visibleUrl":"en.wikipedia.org","title":"\u003cb\u003eDog\u003c/b\u003e - Wikipedia, the free encyclopedia","titleNoFormatting":"Dog - Wikipedia, the free encyclopedia","originalContextUrl":"http://en.wikipedia.org/wiki/Dog","content":"the appropriate-sized \u003cb\u003edog\u003c/b\u003e","contentNoFormatting":"the appropriate-sized dog","tbUrl":"http://t0.gstatic.com/images?q\u003dtbn:ANd9GcTZKvO0mDGuDdifdhW3TEG8bmcPM23DMGEB4wevzBuIPp7HMMwQ3dTetVc"},{"GsearchResultClass":"GimageSearch","width":"170","height":"224","imageId":"ANd9GcTycy7IfwO9VLFIftSa7yNZj1b_BP583qUQ0UmSZnog_jdhdwvewcWvrw","tbWidth":"82","tbHeight":"108","unescapedUrl":"http://upload.wikimedia.org/wikipedia/commons/thumb/a/af/Golden_retriever_eating_pigs_foot.jpg/170px-Golden_retriever_eating_pigs_foot.jpg","url":"http://upload.wikimedia.org/wikipedia/commons/thumb/a/af/Golden_retriever_eating_pigs_foot.jpg/170px-Golden_retriever_eating_pigs_foot.jpg","visibleUrl":"en.wikipedia.org","title":"\u003cb\u003eDog\u003c/b\u003e - Wikipedia, the free encyclopedia","titleNoFormatting":"Dog - Wikipedia, the free encyclopedia","originalContextUrl":"http://en.wikipedia.org/wiki/Dog","content":"See also: \u003cb\u003eDog\u003c/b\u003e food","contentNoFormatting":"See also: Dog food","tbUrl":"http://t1.gstatic.com/images?q\u003dtbn:ANd9GcTycy7IfwO9VLFIftSa7yNZj1b_BP583qUQ0UmSZnog_jdhdwvewcWvrw"},{"GsearchResultClass":"GimageSearch","width":"334","height":"360","imageId":"ANd9GcTsX8rcRiPIMso7akKaQmVP4PzMwoAfbVnlc6KkPNG5jpU7wfyZNWy1oNs","tbWidth":"112","tbHeight":"121","unescapedUrl":"http://www.petscarecenter.com/wp-content/uploads/2011/05/dog.jpg","url":"http://www.petscarecenter.com/wp-content/uploads/2011/05/dog.jpg","visibleUrl":"www.petscarecenter.com","title":"Tips for \u003cb\u003eDog\u003c/b\u003e Care","titleNoFormatting":"Tips for Dog Care","originalContextUrl":"http://www.petscarecenter.com/dog-care/tips-for-dog-care.html","content":"Since \u003cb\u003edogs\u003c/b\u003e are known for the","contentNoFormatting":"Since dogs are known for the","tbUrl":"http://t0.gstatic.com/images?q\u003dtbn:ANd9GcTsX8rcRiPIMso7akKaQmVP4PzMwoAfbVnlc6KkPNG5jpU7wfyZNWy1oNs"},{"GsearchResultClass":"GimageSearch","width":"400","height":"366","imageId":"ANd9GcS6VxIzGltwNb2PWMGDfoBvvuof26Kn9i_BrXYRvgWqpnnT3UNfy5DYyC8","tbWidth":"124","tbHeight":"113","unescapedUrl":"http://static.ddmcdn.com/gif/dog-best-friend-1.jpg","url":"http://static.ddmcdn.com/gif/dog-best-friend-1.jpg","visibleUrl":"animals.howstuffworks.com","title":"Is a \u003cb\u003edog\u003c/b\u003e really a man\u0026#39;s best friend?: \u003cb\u003eDog\u003c/b\u003e Care: Animal Planet","titleNoFormatting":"Is a dog really a man\u0026#39;s best friend?: Dog Care: Animal Planet","originalContextUrl":"http://animals.howstuffworks.com/pets/dog-best-friend.htm","content":"\u003cb\u003eDog\u003c/b\u003e Image Gallery","contentNoFormatting":"Dog Image Gallery","tbUrl":"http://t3.gstatic.com/images?q\u003dtbn:ANd9GcS6VxIzGltwNb2PWMGDfoBvvuof26Kn9i_BrXYRvgWqpnnT3UNfy5DYyC8"}],"cursor":{"resultCount":"3,460,000,000","pages":[{"start":"0","label":1},{"start":"4","label":2},{"start":"8","label":3},{"start":"12","label":4},{"start":"16","label":5},{"start":"20","label":6},{"start":"24","label":7},{"start":"28","label":8}],"estimatedResultCount":"3460000000","currentPageIndex":0,"moreResultsUrl":"http://www.google.com/images?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den\u0026q\u003ddog","searchResultTime":"0.07"}}, "responseDetails": null, "responseStatus": 200}

instead of doing a manual url encoding of your url like you do:
NSString *google = [NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults]objectForKey:#"string"]];
NSString *newGoogle = [google stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *fullGoogle = [NSString stringWithFormat:#"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%#",newGoogle];
NSURL * url = [NSURL URLWithString:fullGoogle];
NSURLRequest * request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Try the method:
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
which does a more accurate encoding of the url:
NSString *google = [NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults]objectForKey:#"string"]];
NSString *fullGoogle = [NSString stringWithFormat:#"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%#",google];
NSString * urlEncoded = [fullGoogle stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL * url = [NSURL URLWithString:urlEncoded];
NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Maybe this is your problem, hope it helps!

You need this in connectionDidFinish
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSDictionary *test = [json objectForKey:#"responseData"];
NSDictionary *closer = [test objectForKey:#"results"];
NSArray *closest = [closer valueForKey:#"url"];

Related

REQUEST_DENIED on ios google map api

I am using
-(void) getRouteData :(double)startPointLatitude :(double)startPointLongitude :(double)stopPointLatitude :(double)stopPointLongitude{
NSString *url = #"http://maps.apple.com/maps/api/directions/json?";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:15];
NSString *postString;
postString = [#"" stringByAppendingFormat: #"origin=%f,%f&destination=%f,%f&sensor=true&mode=driving", startPointLatitude, startPointLongitude, stopPointLatitude, stopPointLongitude];
NSLog(#"%#%#",url, postString);
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
Boolean isDataGet = false;
if (theConnection) {
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *result = [NSString stringWithFormat:#"%#", [self hexToString:data]];
NSLog(#"result = %#", result);
}
}
to draw path initial and final points on google map but I am getting
{
"routes" : [],
"status" : "REQUEST_DENIED"
}
Also when I add api key it does not work either. (I have enabled places API too)
I solved problem by this function
-(void) getRouteData :(double)startPointLatitude :(double)startPointLongitude :(double)stopPointLatitude :(double)stopPointLongitude{
NSString* apiUrlStr = [NSString stringWithFormat:#"http://maps.google.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=true&mode=driving", startPointLatitude, startPointLongitude, stopPointLatitude, stopPointLongitude];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:apiUrlStr]];
[request setTimeoutInterval:15];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
Boolean isDataGet = false;
if (theConnection) {
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *result = [NSString stringWithFormat:#"%#", [self hexToString:data]];
NSLog(#"result = %#", result);
}
}

the search bar in Xcode 5 crashes when i type something

the search bar in Xcode 4.5.1 crashes when i type something, and it worked just fine when i was using Xcode 4.4
please help
i used this code which was an answer for another question, and it worked just fine when i was using Xcode 4/4, until i updated it to 4.5.1
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar{
//Perform the JSON query.
[self searchCoordinatesForAddress:[theSearchBar text]];
//Hide the keyboard.
[theSearchBar resignFirstResponder];}
-(void) searchCoordinatesForAddress:(NSString *)inAddress{
NSMutableString *urlString = [NSMutableString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=json",inAddress];
//Replace Spaces with a '+' character.
[urlString setString:[urlString stringByReplacingOccurrencesOfString:#" " withString:#"+"]];
NSURL *url = [NSURL URLWithString:urlString];
//Setup and start an async download.
//Note that we should test for reachability!.
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSArray *placemark = [results objectForKey:#"Placemark"];
NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:#"Point.coordinates"];
double longitude = [[coordinates objectAtIndex:0] doubleValue];
double latitude = [[coordinates objectAtIndex:1] doubleValue];
[self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];}

Managing two NSURLConnection

I want to do two async request from two different kml file, so I setup two requests first:
NSString *server1URL = [NSString stringWithFormat:...];
NSMutableURLRequest *firstRequest =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:server1URL]];
[firstRequest setHTTPMethod:#"GET"];
NSURLConnection *AConnection = [NSURLConnection connectionWithRequest:firstRequest delegate:self];
NSString *server2URL = [NSString stringWithFormat:...];
NSMutableURLRequest *secondRequest =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:server2URL]];
[secondRequest setHTTPMethod:#"GET"];
NSURLConnection *BConnection = [NSURLConnection connectionWithRequest:secondRequest delegate:self];
Then I init NSMutableData I will be using:
AResponseData = [[NSMutableData alloc] init];
BResponseData = [[NSMutableData alloc] init];
Then, I refer this post and did this:
connectionToInfoMapping = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionaryAddValue(connectionToInfoMapping, AConnection, [NSMutableDictionary dictionaryWithObject:AResponseData forKey:#"receivedData"]);
CFDictionaryAddValue(connectionToInfoMapping, BConnection, [NSMutableDictionary dictionaryWithObject:BResponseData forKey:#"receivedData"]);
OK, then there're delegates:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
const NSMutableDictionary *connectionInfo = CFDictionaryGetValue(connectionToInfoMapping, connection);
[[connectionInfo objectForKey:#"receivedData"] appendData:data];
}
So with this I can get data append to the correct NSMutableData that matches the connection.
Now in - (void)connectionDidFinishLoading:(NSURLConnection *)connection, I want to "If A finish, do this, if B finish, do this", and my question is, how can I do this?
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if( [connection isEqual: AConnection] ){
// do connection A stuff
}
else if( [connection isEqual: BConnection] ){
// do connection B stuff
}
}
Use GCD with sendSynchronousRequest: requests, they will be run in the background.
Example:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSURLRequest *request = [NSURLRequest requestWithURL:url1];
NSURLResponse *response;
NSError *error;
NSData *data1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// do something with the data
});
dispatch_async(queue, ^{
NSURLRequest *request = [NSURLRequest requestWithURL:url2];
NSURLResponse *response;
NSError *error;
NSData *data2 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// do something with the data
});
How about assigning tags to each connection and checking the tags via an if/else or switch in the connectionDidFinishLoading?

How to post a string to web server url in iphone sdk?

How can I post a string(i.e) a word to web server url in iphone sdk?
Some sample codes or tutorials would be appreciated.
Thanking you.
This may help you, although I havent tested it:
NSMutableString *httpBodyString;
NSURL *url;
NSMutableString *urlString;
httpBodyString=[[NSMutableString alloc] initWithString:#"Name=The Big Bopper&Subject=Hello Baby&MsgBody=...You knooow what I like...Chantilly lace..."];
urlString=[[NSMutableString alloc] initWithString:#"http://www.somedomain.com/contactform.php"];
url=[[NSURL alloc] initWithString:urlString];
[urlString release];
NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
[url release];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[httpBodyString dataUsingEncoding:NSISOLatin1StringEncoding]];
[httpBodyString release];
NSURLConnection *connectionResponse = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if (!connectionResponse)
{
NSLog(#"Failed to submit request");
}
else
{
NSLog(#"--------- Request submitted ---------");
NSLog(#"connection: %# method: %#, encoded body: %#, body: %a", connectionResponse, [urlRequest HTTPMethod], [urlRequest HTTPBody], httpBodyString);
NSLog(#"New connection retain count: %d", [connectionResponse retainCount]);
responseData=[[NSMutableData data] retain];
NSLog(#"response", responseData);
}
Source: http://www.iphonedevsdk.com/forum/iphone-sdk-development/6341-help-executing-http-url-post-variables.html
You can post the string to webservice in so many ways, In those one is
Using Rest protocol:
It has two sub types, HTTP GET, HTTP POST. The Http Get is simple.
You can add the value to the attribute and you can directly call the service.
Check the following code.
NSString *url = #"http://123.456.789.0?action=get_movies";
Here the I am passing the get_movies string to the server to the action attribute.
and then follow the code for requesting to server.
NSURL *reqUrl = [[NSURL alloc] initWithString:url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:reqUrl];
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSStringEncoding responseEncoding = NSUTF8StringEncoding;
if ([response textEncodingName]) {
CFStringEncoding cfStringEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)[response textEncodingName]);
if (cfStringEncoding != kCFStringEncodingInvalidId) {
responseEncoding = CFStringConvertEncodingToNSStringEncoding(cfStringEncoding);
}
}
[reqUrl release];
NSString *dataString = [[NSString alloc] initWithData:data encoding:responseEncoding];
the dataString is the responseString from the server. You can use that.
Regards,
Satya.

NSURL not working

I wanted to ask if anyone could help he get this code to work. Nothing is showing up in my MySQL database. Thanks, enbr.
NSString *urlstr = [[NSString alloc] initWithFormat:#"http://mysite.come/myapp/submitrating.php?name=%#&comment=%#&rating=%#",
[selectedItem objectForKey:#"name"], comment.text, selectedRating];
NSString *urlstrEncoded = [urlstr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:urlstrEncoded];
[urlstr release];
[url release];
You need to do much more than that! At minimum you need the following:
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
along with implementing the following methods:
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
You're not doing anything with the URL object except creating it. Perhaps you want to try an NSURLConnection?
I got it to work with this code.
NSString *urlstr = [NSString stringWithFormat:#"http://mysite.com/myapp/submitrating.php?name=%#&comment=%#&rating=%#", [selectedItem objectForKey:#"name"], comment.text, selectedRating];
NSString *urlEncoded = [urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:urlEncoded];
NSString *ans = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];