I'm using this code to open iTunes Store app and search for specific music:
NSString *iTunesLink = [NSString stringWithFormat:#"http://search.itunes.apple.com/WebObjects/MZSearch.woa/wa/search?entity=album&media=all&page=1&restrict=true&startIndex=0&term=TERM_NAME"];
NSURL *url = [NSURL URLWithString:iTunesLink];
[[UIApplication sharedApplication] openURL:url];
Code works fine on iOS7, by changing TERM_NAME value I can search whatever I want. The issue on iOS8 is that somehow search term is appended and prepended by ( " ) symbols. I'm using log to check what's the value of my NSURL but it looks fine.
This code worked for me:
NSString *artist = #"artist";
NSString *title = #"title";
NSOperationQueue *operationQueue = [NSOperationQueue new];
NSString *baseURLString = #"https://itunes.apple.com/search";
NSString *searchTerm = [NSString stringWithFormat:#"%# %#", artist, title];
NSString *searchUrlString = [NSString stringWithFormat:#"%#?media=music&entity=song&term=%#&artistTerm=%#&songTerm=%#", baseURLString, searchTerm, artist, title];
searchUrlString = [searchUrlString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
searchUrlString = [searchUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *searchUrl = [NSURL URLWithString:searchUrlString];
NSURLRequest *request = [NSURLRequest requestWithURL:searchUrl];
[NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse* response, NSData* data, NSError* error)
{
if (error)
{
NSLog(#"Error: %#", error);
}
else
{
NSError *jsonError = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError)
{
NSLog(#"JSON Error: %#", jsonError);
}
else
{
NSArray *resultsArray = dict[#"results"];
if(resultsArray.count == 0)
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"917xfm" message:[NSString stringWithFormat:#"No results returned."] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
});
}
else
{
NSDictionary *trackDict = resultsArray[0];
NSString *trackViewUrlString = trackDict[#"trackViewUrl"];
if (trackViewUrlString.length)
{
NSURL *trackViewUrl = [NSURL URLWithString:trackViewUrlString];
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] openURL:trackViewUrl];
});
}
}
}
}
}];
Related
I didn't get correct results for Forward geocoding in certain cases. When I search for some places or hotel it shows result of some others places or areas. I have got following code. I study the following link. What url should i place to get correct results.
how can we implement the following given in following site
https://developers.google.com/places/webservice/autocomplete
A request for addresses containing "Vict" with results in French:
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Vict&types=geocode&language=fr&key=API_KEY
A request for cities containing "Vict" with results in Brazilian
Portuguese:
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Vict&types=(cities)&language=pt_BR&key=API_KEY
I have implemented following but it doesn't give the results as i aspected
- (CLLocationCoordinate2D)addressLocation{
NSError *error = nil;
// NSString *lookUpString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true", SearchtextField];
// NSString *API_KEY=#"AIzaSyB27SkGBzvEYKcxvZ5nmOVWvrA-6Xqf-7A";
NSString *API_KEY=#"AIzaSyCHcqJcqZbP1XpU-WB4VfRct5hpdgqisSY";
NSString *lookUpString = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/geocode/json?address=%#®ion=np&key=%#", SearchtextField,API_KEY];
lookUpString = [lookUpString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookUpString]];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
NSArray *locationArray = [[[jsonDict valueForKey:#"results"] valueForKey:#"geometry"] valueForKey:#"location"];
NSString *statusString = [jsonDict valueForKey:#"status"];
if ([statusString isEqualToString:#"OK"])
{
locationArray = [locationArray objectAtIndex:0];
Str_Latitude= [locationArray valueForKey:#"lat"];
Str_Longitude= [locationArray valueForKey:#"lng"];
NSLog(#"LatitudeString:%# & LongitudeString:%#", Str_Latitude, Str_Longitude);
/*Google place latitude Longitude*/
Arr_LatLong = #[Str_Latitude,Str_Longitude];
[[NSUserDefaults standardUserDefaults] setValue:Str_Latitude forKey:#"Str_Latitude"];
[[NSUserDefaults standardUserDefaults] setValue:Str_Longitude forKey:#"Str_Longitude"];
[[NSUserDefaults standardUserDefaults] synchronize];
GogLatitude = [Str_Latitude doubleValue];
Goglongitude = [Str_Longitude doubleValue];
if (Bool_SearchField) {
[self getGoogleAddress];
Bool_SearchField=FALSE;
}else{
}
}else{
UIAlertView *alertview =[[UIAlertView alloc] initWithTitle:#"Address not found" message:#"make sure you enter a valid address" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertview show];
NSLog(#"Something went wrong, couldn't find address");
[self.tableView reloadData];
}
GogLocation.latitude = GogLatitude;
GogLocation.longitude = Goglongitude;
return GogLocation;
}
When i search for radission in maps.google.com it shows as below
But when i search in my app it shows different locations then what I search
You can either take use of the Region Biasing, which according to wiki, should be NP. So add ®ion=np at the end of your query.
Or you can use the Viewport Biasing to set the bounds of your searches.
I have done what you have asked in one of my apps, but the url is different.
I am posting the function that gets called each time i input something in a text field.
-(void) startAutocomplete{
NSString* baseUrl = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/queryautocomplete/json?input=%#&key=AIzaSyDz3HAmNY8NsgIhtA8gtbH-QA08Lg9tej4&types=all", self.locationTextfield.text];
NSURL *url = [NSURL URLWithString:[baseUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"Url: %#", url);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError!=nil) {
[[[UIAlertView alloc] initWithTitle:nil message:connectionError.localizedDescription delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil] show ] ;
}else{
NSError *error = nil;
self.searchResult= [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
//NSLog(#"result:%#",self.searchResult);
[self.tableView reloadData];
}
}];
}
I want to get address from latitude and longitude with GoogleGEO CODING (EX URL = http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true_or_false )
So I want to get JSON from that page by AFNetworking.
It's my code below :
IBAction)reLocation:(UIButton*)sender
{
if(sender.tag==1)
{
NSArray *gpsValue = [self getGPS];
float lat = [[gpsValue objectAtIndex:0] floatValue];
float lon = [[gpsValue objectAtIndex:1] floatValue];
NSString *string = [NSString stringWithFormat:#"%#%#,%#&sensor=true_or_false",GEOCODING_URL,[NSString stringWithFormat:#"%f", lat],[NSString stringWithFormat:#"%f",lon]]; // NSString *str = [NSString stringWithFormat:#"%f", myFloat];
NSLog(string);
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"AFNetworking success");
NSDictionary *location = (NSDictionary *)responseObject;
// 3
self.title = #"JSON Retrieved";
//[self.tableView reloadData];
NSLog(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"AFNetworking failure");
switch (operation.response.statusCode) {
case 400:
// Do stuff
NSLog(#"error 400");
break;
default:
NSLog([NSString stringWithFormat:#"%ld",(long)operation.response.statusCode]);
break;
}
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}}
But when I click my button, always afnetworking fails and log shows 0 for status code.
I also got url log that i put in
i already checked that url is not problem (it shows json in working order)
I debug with simulator!
Is there something I miss ?
I am doing a database based application. My app needs to update a database table and simultaneously it needs to update the table view i.e. generated based on that particular database table.
Here's is the code i have written
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.courses.count;
}
-(void)viewWillAppear:(BOOL)animated {
self.usernameLBL.text = [NSString stringWithFormat:#"Welcome, %#", self.del.username];
[self loadCourses];
// NSLog(#"The courses count is %d", self.courses.count);
}
-(void)loadCourses {
NSString * stringUrl = [NSString stringWithFormat:"Some URL";
NSURL * uRL = [NSURL URLWithString:[stringUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest * request = [NSURLRequest requestWithURL:uRL];
NSError * error;
NSData * results = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
self.courses = [NSJSONSerialization JSONObjectWithData:results options:0 error:&error];
NSLog(#"The courses array count is %d", self.courses.count);
[self.tableView reloadData];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSDictionary * dict = self.courses[indexPath.row];
cell.textLabel.text = dict[#"name"];
cell.detailTextLabel.text = dict[#"id"];
return cell;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.courses = [[NSMutableArray alloc] init];
self.del = [[UIApplication sharedApplication] delegate];
NSString * strURL = [NSString stringWithFormat:"Some URL";
// NSLog(#"The username is %#", self.del.username);
NSURL * url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSError * error;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
// NSLog(#"The data is %#", data);
NSDictionary * result = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
// NSLog(#"The error is %#", error);
// NSLog(#"The value returned is %#", result[#"image"]);
if(![result[#"image"] isEqualToString:#"empty"]){
NSString * urlLocation = result[#"image"];
self.adminIMG.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[urlLocation stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]]];
}
// Do any additional setup after loading the view.
}
- (IBAction)addNewCourse:(id)sender {
NSString * strURL = [NSString stringWithFormat:"Some URL";
NSURL * url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSError * error;
NSData * results = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:results options:0 error:&error];
if([dict[#"response"] isEqualToString:#"success"]) {
NSLog(#"New course added");
UIAlertView * success = [[UIAlertView alloc] initWithTitle:#"New course added successfully" message:#"You successfully added a new course" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[success show];
}else {
NSLog(#"Course not added");
}
[self.courses removeAllObjects];
[self viewDidLoad];
[self viewWillAppear:YES];
}
And i got this error.
Error: Evaluation[13335:60b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKeyedSubscript:]: unrecognized selector sent to instance 0xb7d26d0'
I tried many solutions available on the internet but those are not working for me. Anyone can help me, please. Thanks in advance :)
your issue might be here
[self.courses removeAllObjects];
[self viewDidLoad];
[self viewWillAppear:YES];
you don't have to clear your array, try this:
function:
- (void)addCourse{
NSString * strURL = [NSString stringWithFormat:"Some URL";
NSURL * url = [NSURL URLWithString:
[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSError * error;
NSData * results = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:&error];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:results
options:0 error:&error];
if([dict[#"response"] isEqualToString:#"success"]) {
NSLog(#"New course added");
UIAlertView * success = [[UIAlertView alloc]
initWithTitle:#"New course added successfully"
message:#"You successfully added a new course"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[success show];
}else {
NSLog(#"Course not added");
}
}
Your IBAction keep it simple there you don't want to fire off life cycle event from an IBAction instead call the methods you need not to mention that it is not a good idea to call viewDidLoad before viewWillAppear Method...
- (IBAction)addNewCourse:(id)sender {
[self addCourse];
[self loadCourses];
}
first you check the array data it valid or not .(put break point and check it)
and i think u got error because u still not convert integer to string .
i replace this line in to tableview cellForRowAtIndexPath:
cell.detailTextLabel.text = dict[#"id"];
to replace
cell.detailTextLabel.text =[NSString stringWithFormat:#"%d",dict[#"id"]];
Its may be very helpful to you Thanks.
I think your problem is here.. your targeting AppDelegate as self.delegate
self.del = [[UIApplication sharedApplication] delegate];
And AppDelegate runs onetime at start of application only that's why your are getting error
I got one sample code (iOS) in which I am getting all user's friends (App Id = 377766775651612) but when I using own created app id (app id 707496825976004), I am getting the list of friends who are using my app.
I want all friends
Please help me
Thanks in advance
This is not possible with Graph API version 2.0.
This is not possible with Graph API version 2.0. Any app made after april 2014 will use 2.0. For more details, see this answer:
Get facebook friends with Graph API v.2.0
-(IBAction)permit:(id)sender
{
if ( [facebook isEqualToString:#"yes"])
{
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle: #"Status!"
message: #"Please Log in first"
delegate: self
cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[Alert show];
}
else
{
[self requestPermissionAndPost];
}
}
- (void)requestPermissionAndPost {
[FBSession.activeSession requestNewPublishPermissions:[NSArray arrayWithObjects:#"publish_actions",#"publish_stream",#"friends_birthday", nil]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error && [FBSession.activeSession.permissions indexOfObject:#"publish_actions"] != NSNotFound) {
[self getFriends];
} else if (error) {
if ([FBErrorUtility errorCategoryForError:error] != FBErrorCategoryUserCancelled) {
NSLog(#"error %#",error);
}
}
}];
}
-(void)getFriends
{
[self addMBProgress];
NSString *accsstoken=[[[FBSession activeSession]accessTokenData]accessToken];
NSString *abcd=[NSString stringWithFormat:#"https://graph.facebook.com/me/friends?fields=id,name,picture,birthday,location,email&access_token=%#",accsstoken];
NSURL *url = [NSURL URLWithString:abcd];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL: url];
[request1 setURL:url];
[request1 setHTTPMethod:#"GET"];
NSError *error;
NSURLResponse *response;
urlDataaa = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&response error:&error];
if (urlDataaa!=nil)
{
if(NSClassFromString(#"NSJSONSerialization"))
{
NSError *error = nil;
id object = [NSJSONSerialization
JSONObjectWithData:urlDataaa
options:0
error:&error];
if(error)
{
}
if([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *results = object;
NSLog(#"results..:%#",results);
[self removeMBProgress];
venues = [results objectForKey:#"data"];
NSLog(#"birthday..%#",venues);
}
}
}
[venues enumerateObjectsUsingBlock:^(NSDictionary *dict,NSUInteger idx,BOOL *stop)
{
NSString *namess = [dict objectForKey:#"name"];
[name addObject:namess];
if ([dict objectForKey:#"birthday"]) {
NSString *birthdayss = [dict objectForKey:#"birthday"];
[birthday addObject:birthdayss];
}
else
{
[birthday addObject:#"No Birthday"];
}
}
];
NSString *query1 = [NSString stringWithFormat:#"DELETE from userdata"];
[[DBManager sharedDatabase]executeQuery:query1];
NSLog(#"query1:%#",query1);
userdata = [[DBManager sharedDatabase]userdata:#"select * from userdata"];
NSLog(#"userdata...%#",userdata);
for (int i=0; i<[name count]; i++)
{
NSString *namesss =[name objectAtIndex:i];
NSString *datesss =[birthday objectAtIndex:i];
NSString *query1 = [NSString stringWithFormat:#"INSERT INTO userdata (name,date) VALUES (\"%#\",\"%#\")",namesss,datesss];
NSLog(#"query1:%#",query1);
[[DBManager sharedDatabase]executeQuery:query1];
}
userdata = [[DBManager sharedDatabase]userdata:#"select * from userdata"];
NSLog(#"userdata...%#",userdata);
[userdata addObjectsFromArray:manualdata];
[tempSearchData removeAllObjects];
[tempSearchData addObjectsFromArray:userdata];
NSLog(#"tempSearchData..%#",tempSearchData);
[friendlist reloadData];
}
From Facebook sdk version 2.0 onwards, they changing the response like that(getting the list of friends who are using my app).I think from a particular date onwards its behave like that.if u register a new app in developer site ,it may behave like that only.
i'm new to blocks, I have a class of requests with static methods to call me back on UIViewControllers with some blocks
this is the method implementation :
(putting a breakpoint on the block(something) DOES stop there, like it should)
+(void)requestSuggestedLocationsForText:(NSString*)text withBlock:(void (^)(NSArray*callBackArray))block
{
if ([text isEqualToString:#""] || [text isEqualToString:#" "])
{
block(nil);
return;
}
NSString * key = #"someActualKeyHere";
;
NSString * finalText;
NSArray *tagschemes = [NSArray arrayWithObjects:NSLinguisticTagSchemeLanguage, nil];
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:tagschemes options:0];
[tagger setString:text];
NSString *language = [tagger tagAtIndex:0 scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];
if ([language isEqualToString:#"he"])
{
finalText = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
else
{
finalText = [text stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
}
NSString *urlString = [NSString stringWithFormat:
#"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%#&types=geocode&sensor=true&key=%#",finalText,key];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (!responseObject && ![responseObject respondsToSelector:#selector(dataWithData:)])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving "
message:#"ERROR"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
return ;
}
NSData * responseData = [NSData dataWithData:responseObject];
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
NSError *err;
if ([responseString respondsToSelector:#selector(JSONObjectWithData:options:error:)])
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&err];
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}
this is how I call it, notice the NSLog, i put a breakpoint on it and its never called
which is exactly what I want to occur.
[Requests requestSuggestedLocationsForText:text withBlock:^(NSArray *callBackArray)
{
NSLog(#"ROFL");
}];
for the record, I have tried the same method with a different signature (without the returning variable name like so :
+(void)requestSuggestedLocationsForText:(NSString*)text withBlock:(void (^)(NSArray*))block;
still didn't fire my breakpoint :(
I think that this:
if ([responseString respondsToSelector:#selector(JSONObjectWithData:options:error:)])
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&err];
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
Never runs because as far as I know, NSString doesn't declare JSONObjectWithData. Your break point will never hit because it will never be called.
It seems like it could just be:
NSData * responseData = [NSData dataWithData:responseObject];
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (!err) {
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
else {
block(nil);
}
The other way you convert it to a string, then back to data, why not just keep it as data?