I am assigned to work with foursquare just recently. I have an app that needs to be authenticated and access the foursquare environment. I am having trouble with the following code to access checkins. I had already successfully made the authentication but the thing is that when I made a check in request, an errorType invalid_auth code 401 appears. I just don't know what's wrong with this.
Here is my full code; I am using fsq wrapper I found in github:
#import "FSQViewController.h"
#define kClientID #"XXXXXXXXXXXXXXXXXXXXXXX"
#define kCallbackURL #"invitation://foursquare"
#interface FSQViewController()
#property(nonatomic,readwrite,strong) BZFoursquare *foursquare;
#property(nonatomic,strong) BZFoursquareRequest *request;
#property(nonatomic,copy) NSDictionary *meta;
#property(nonatomic,copy) NSArray *notifications;
#property(nonatomic,copy) NSDictionary *response;
#end
#implementation FSQViewController
#synthesize foursquare = foursquare_;
#synthesize request = request_;
#synthesize meta = meta_;
#synthesize notifications = notifications_;
#synthesize response = response_;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (id) initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if(self){
self.foursquare = [[BZFoursquare alloc]initWithClientID:kClientID callbackURL:kCallbackURL];
foursquare_.version = #"20120206";
foursquare_.locale = [[NSLocale currentLocale]objectForKey:NSLocaleLanguageCode];
foursquare_.sessionDelegate = (id<BZFoursquareSessionDelegate>) self;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark -
#pragma mark BZFoursquareRequestDelegate
- (void)requestDidFinishLoading:(BZFoursquareRequest *)request {
NSLog(#"test");
self.meta = request.meta;
self.notifications = request.notifications;
self.response = request.response;
self.request = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)request:(BZFoursquareRequest *)request didFailWithError:(NSError *)error {
NSLog(#"HERE > %s: %#", __PRETTY_FUNCTION__, error);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:[[error userInfo] objectForKey:#"errorDetail"] delegate:nil cancelButtonTitle:NSLocalizedString(#"OK", #"") otherButtonTitles:nil];
[alertView show];
self.meta = request.meta;
self.notifications = request.notifications;
self.response = request.response;
self.request = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
#pragma mark -
#pragma mark BZFoursquareSessionDelegate
- (void)foursquareDidAuthorize:(BZFoursquare *)foursquare {
NSLog(#"authorized!");
}
- (void)foursquareDidNotAuthorize:(BZFoursquare *)foursquare error:(NSDictionary *)errorInfo {
NSLog(#"not authorized! %s: %#", __PRETTY_FUNCTION__, errorInfo);
}
- (IBAction)click:(id)sender {
if (![foursquare_ isSessionValid]){
NSLog(#"here");
[foursquare_ startAuthorization];
} else {
[foursquare_ invalidateSession];
}
}
- (IBAction)checkin:(id)sender {
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:#"4d341a00306160fcf0fc6a88", #"venueId", #"public", #"broadcast", kClientID, #"oauth_token", nil];
self.request = [foursquare_ requestWithPath:#"checkins/add" HTTPMethod:#"POST" parameters:parameters delegate:self];
[request_ start];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
#end
can you help me guys? any help will highly be appreciated.
https://developer.foursquare.com/overview/responses
401 (Unauthorized) The OAuth token was provided but was invalid.
Might you have somehow corrupted your oauth token?
I am using the code below & it is working for me :
NSDictionary *parameters = #{#"venueId": #"4a0c6465f964a5202a751fe3", #"broadcast": #"public",#"oauth_token":kClientID};
Related
I'm trying to write a weather app that use wunderground api...
I've got an apiKey and I used it in the code below, but I can't see any result in debug area...
Xcode show me a warning in a line "EXPRESSION RESULT UNUSED"...Is this the problem?
Can anybody help me please?
#import "WeatherForecast.h"
#import "MainViewController.h"
#implementation WeatherForecast
- (void) queryServiceWithState:(NSString *)state
andCity:(NSString *)city
withParent:(UIViewController *)controller {
viewController = (MainViewController *)controller;
responseData = [NSMutableData data];
apiKey = #"c5f79118382c6e91";
NSString *url =
[NSString stringWithFormat:
#"http://api.wunderground.com/api/%#/conditions/q/%#//%#.xml",
apiKey, state, city];
theURL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:theURL];
[[NSURLConnection alloc] initWithRequest:request delegate:self];//EXPRESSION RESULT UNUSED
}
#pragma mark NSURLConnection Delegate Methods
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)response{
#autoreleasepool {
theURL = [request URL];
}
return request;
}
- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection
didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Error = %#",error);
}
- (void)connectionDidFinishiLoading: (NSURLConnection *)connection {
NSString *content =
[[NSString alloc]initWithBytes:[responseData bytes]
length:[responseData length]
encoding:NSUTF8StringEncoding];
NSLog ( #"Data = %#",content);
//...Insert code to parse the content here...
[viewController updateView];
}
#end
I've got another 2 .m files for my app, maybe the error is in one of this
#import "MainViewController.h"
#import "WeatherForecast.h"
#interface MainViewController ()
#end
#implementation MainViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self refreshView:self];
}
- (IBAction)refreshView:(id)sender {
[loadingActivityIndicator startAnimating];
[self.forecast queryServiceWithState:#"UK" andCity:#"London" withParent:self];
}
- (void)updateView {
//...
[loadingActivityIndicator stopAnimating];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Flipside View
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)showInfo:(id)sender
{
FlipsideViewController *controller = [[FlipsideViewController alloc]
initWithNibName:#"FlipsideViewController" bundle:nil];
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:controller animated:YES completion:nil];
}
#end
And
#import "AppDelegate.h"
#import "WeatherForecast.h"
#import "MainViewController.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.mainViewController = [[MainViewController alloc]
initWithNibName:#"MainViewController" bundle:nil];
WeatherForecast *forecast = [[WeatherForecast alloc] init];
self.mainViewController.forecast = forecast;
self.window.rootViewController = self.mainViewController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
}
- (void)applicationWillTerminate:(UIApplication *)application
{
}
#end
If I try to turn off internet connection I can see in the debug area the "Error message", but if I turn on internet connection, so I only see the Activity Indicator spinning forever...
Thank you for your response....I feel lost...
Where you get EXPRESSION RESULT UNUSED is the connection object. You should usually be storing that into a property so you ensure that it isn't destroyed while you're still using it.
I have used Core location framework to receive my GPS coordinates in my IPOD.First time i can get the Latitude and longitude, then i got an error message , kCLErrorDomain Code=0 Operation Could not be completed.
But the error message never change.I think first time only it works
This is My code
#import "CoreLocationDemoViewController.h"
#implementation CoreLocationDemoViewController
#synthesize CLController;
- (void)viewDidLoad {
[super viewDidLoad];
CLController = [[CoreLocationController alloc] init];
CLController.delegate = self;
[CLController.locMgr startUpdatingLocation];
}
- (void)locationUpdate:(CLLocation *)location {
speedLabel.text = [NSString stringWithFormat:#"SPEED: %f", [location speed]];
latitudeLabel.text = [NSString stringWithFormat:#"LATITUDE: %f", location.coordinate.latitude];
longitudeLabel.text = [NSString stringWithFormat:#"LONGITUDE: %f", location.coordinate.longitude];
altitudeLabel.text = [NSString stringWithFormat:#"ALTITUDE: %f", [location altitude]];
errorLabel.text = #"";
}
- (void)locationError:(NSError *)error {
if(!CLController) //.text )
{
errorLabel.text = [error description];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
return YES;
}
- (void)viewDidUnload {
}
- (void)dealloc {
[CLController release];
[super dealloc];
}
#end
Anybody know what are the issues, help is highly appreciated.
Thanks,
VKS
Yes iPod doesn't have GPS functionality. Test your app either in simulator or iPhone not on iPod.
How can I get the username once anyone is logged in to facebook through my app ?
I am using :-
FBConnect API.
My Controller.m file-
#import "FacebookPOCViewController.h"
#implementation FacebookPOCViewController
#synthesize session = _session;
#synthesize logoutButton = _logoutButton;
#synthesize loginDialog = _loginDialog;
#synthesize facebookName = _facebookName;
- (void)viewDidLoad {
//PayTai Facebook App
static NSString* kApiKey = #"230600000000";
static NSString* kApiSecret = #"----------------------";
_session = [[FBSession sessionForApplication:kApiKey secret:kApiSecret delegate:self] retain];
// Load a previous session from disk if available. Note this will call session:didLogin if a valid session exists.
[_session resume];
[super viewDidLoad];
}
- (IBAction)loginTapped:(id)sender {
//_posting = YES;
// If we're not logged in, log in first...
if (![_session isConnected]) {
self.loginDialog = nil;
_loginDialog = [[FBLoginDialog alloc] init];
[_loginDialog show];
}
// If we have a session and a name, post to the wall!
else if (_facebookName != nil) {
//[self postToWall];
printf("Session");
}
// Otherwise, we don't have a name yet, just wait for that to come through.
}
- (IBAction)logoutButtonTapped:(id)sender {
[_session logout];
}
#pragma mark FBSessionDelegate methods
- (void)session:(FBSession*)session didLogin:(FBUID)uid {
[self getFacebookName];
}
- (void)session:(FBSession*)session willLogout:(FBUID)uid {
_logoutButton.hidden = YES;
_facebookName = nil;
}
pragma mark Get Facebook Name Helper
- (void)getFacebookName {
NSString* fql = [NSString stringWithFormat:#"select uid,name from user where uid == %lld", _session.uid];
//NSLog(#"%#",_session.uid);
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:#"query"];
[[FBRequest requestWithDelegate:self] call:#"facebook.fql.query" params:params];
}
#pragma mark FBRequestDelegate methods
- (void)request:(FBRequest*)request didLoad:(id)result {
if ([request.method isEqualToString:#"facebook.fql.query"]) {
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:#"name"];
self.facebookName = name;
_logoutButton.hidden = NO;
[_logoutButton setTitle:[NSString stringWithFormat:#"Logout as %#", name] forState:UIControlStateNormal];
//if (_posting) {
// [self postToWall];
// _posting = NO;
// }
}
}
Take a look at this. You can get almost any info of the user with the GRAPH api.
http://developers.facebook.com/docs/reference/api/user/
Example
/**
* Request the facebook name for the user
* Response will be obtained on delegate
*/
- (void) getFacebookName {
[facebook requestWithGraphPath:#"me?fields=id,name" andDelegate:self];
}
#pragma mark - FBRequestDelegate methods
- (void)request:(FBRequest *)request didLoad:(id)result {
NSLog(#"Result: %#", result);
NSDictionary *userInfo = (NSDictionary *)result;
userName = [userInfo objectForKey:#"name"];
fb_id = [userInfo objectForKey:#"id"];
}
Hi all
Just wondering how I modify my code to post a score to Facebook
Currently all working with the following posting to facebook, just no score
#import "GameOverViewController.h"
#import "SoundEffects.h"
#import "FBConnect.h"
#implementation GameOverViewController
#synthesize scoreLabel, highScore;
#synthesize session = _session;
#synthesize postScoreButton = _postScoreButton;
#synthesize logoutButton = _logoutButton;
#synthesize loginDialog = _loginDialog;
#synthesize facebookName = _facebookName;
#synthesize posting = _posting;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *gameOverPath = [[NSBundle mainBundle] pathForResource:#"gameover" ofType:#"png"];
UIImage *gameOver = [[UIImage alloc] initWithContentsOfFile: gameOverPath];
UIImageView *gameOverViewTemp = [[UIImageView alloc] initWithImage:gameOver];
[self.view addSubview:gameOverViewTemp];
gameOverText = [SpriteHelpers setupAnimatedSprite:self.view numFrames:3 withFilePrefix:#"gameovertext" withDuration:0.4 ofType:#"png" withValue:0];
gameOverText.center = CGPointMake(160, 90);
scoreLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 320, 70)];
scoreLabel.text = [NSString stringWithFormat:#"%d points", highScore];
[self.view addSubview:scoreLabel];
scoreLabel.textColor = [UIColor whiteColor];
scoreLabel.backgroundColor = [UIColor clearColor];
scoreLabel.font = [UIFont boldSystemFontOfSize:42];
scoreLabel.textAlignment = UITextAlignmentCenter;
[gameOverViewTemp release];
[gameOver release];
// Set these values from your application page on http://www.facebook.com/developers
// Keep in mind that this method is not as secure as using the sessionForApplication:getSessionProxy:delegate method!
// These values are from a dummy facebook app I made called MyGrades - feel free to play around!
static NSString* kApiKey = #"2af22b07c9730d3d502a7a401b9e48d7";
static NSString* kApiSecret = #"738116a372130f659a761078de08b3d4";
_session = [[FBSession sessionForApplication:kApiKey secret:kApiSecret delegate:self] retain];
// Load a previous session from disk if available. Note this will call session:didLogin if a valid session exists.
[_session resume];
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view removeFromSuperview];
[self release];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (IBAction)postScoreTapped:(id)sender {
_posting = YES;
// If we're not logged in, log in first...
if (![_session isConnected]) {
self.loginDialog = nil;
_loginDialog = [[FBLoginDialog alloc] init];
[_loginDialog show];
}
// If we have a session and a name, post to the wall!
else if (_facebookName != nil) {
[self postToWall];
}
// Otherwise, we don't have a name yet, just wait for that to come through.
}
- (IBAction)logoutButtonTapped:(id)sender {
[_session logout];
}
#pragma mark FBSessionDelegate methods
- (void)session:(FBSession*)session didLogin:(FBUID)uid {
[self getFacebookName];
}
- (void)session:(FBSession*)session willLogout:(FBUID)uid {
_logoutButton.hidden = YES;
_facebookName = nil;
}
#pragma mark Get Facebook Name Helper
- (void)getFacebookName {
NSString* fql = [NSString stringWithFormat:
#"select uid,name from user where uid == %lld", _session.uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:#"query"];
[[FBRequest requestWithDelegate:self] call:#"facebook.fql.query" params:params];
}
#pragma mark FBRequestDelegate methods
- (void)request:(FBRequest*)request didLoad:(id)result {
if ([request.method isEqualToString:#"facebook.fql.query"]) {
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:#"name"];
self.facebookName = name;
_logoutButton.hidden = NO;
[_logoutButton setTitle:[NSString stringWithFormat:#"Facebook: Logout as %#", name] forState:UIControlStateNormal];
if (_posting) {
[self postToWall];
_posting = NO;
}
}
}
#pragma mark Post to Wall Helper
- (void)postToWall {
FBStreamDialog* dialog = [[[FBStreamDialog alloc] init] autorelease];
dialog.userMessagePrompt = #"Enter your message:";
dialog.attachment = [NSString stringWithFormat:#"{\"name\":\"%# just played SpaceRide on the iPhone!\",\"href\":\"http://www.spaceride.me/\",\"caption\":\"%# must be really skillful!\",\"description\":\"\",\"media\":[{\"type\":\"image\",\"src\":\"http://www.spaceride.me/fbicon.png\",\"href\":\"http://www.spaceride.me/\"}]}",
_facebookName, _facebookName];
dialog.actionLinks = #"[{\"text\":\"Get SpaceRide!\",\"href\":\"http://www.spaceride.me/\"}]";
[dialog show];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[scoreLabel release];
[super dealloc];
}
#end
Change:
dialog.attachment = [NSString stringWithFormat:#"{\"name\":\"%# just played SpaceRide on the iPhone!\",\"href\":\"http://www.spaceride.me/\",\"caption\":\"%# must be really skillful!\",\"description\":\"\",\"media\":[{\"type\":\"image\",\"src\":\"http://www.spaceride.me/fbicon.png\",\"href\":\"http://www.spaceride.me/\"}]}",
_facebookName, _facebookName];
To something like:
dialog.attachment = [NSString stringWithFormat:#"{\"name\":\"%# just got %d playing SpaceRide on the iPhone!\",\"href\":\"http://www.spaceride.me/\",\"caption\":\"%# must be really skillful!\",\"description\":\"\",\"media\":[{\"type\":\"image\",\"src\":\"http://www.spaceride.me/fbicon.png\",\"href\":\"http://www.spaceride.me/\"}]}",
_facebookName, score, _facebookName];
Change 'score' to the name of your integer score variable.
We are developing an iPhone app and need to know the user's approximate location. We are using CoreLocation. We can do it ok in suburban environments, but in New York City - we're not able to get any longitude/latitude info.
We suspect it's cos GPS signals are weak among highrises... But shouldn't we still be able to get some approximate location info back?
Any ideas on what may cause/fix this? Thanks.
#import "RootViewController.h"
#import "SlickEatsAppDelegate.h"
#import "SlickEatsWelcomePage.h"
#import "XMLParserShowTodaysOffer.h"
#import "SlickEatsSplashScreen.h"
#implementation RootViewController
#synthesize locationManager,currentLocation,appDelegate;
#synthesize getStartedButton,splashLogoImageView,howItWorkImageView,workButton,infoView;
#synthesize xmlParserShowTodaysOffer;//activityIndicator
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
[self connectedToNetwork];
self.navigationController.navigationBar.hidden = TRUE;
if(locationManager == nil)
{
[[self locationManager] startUpdatingLocation];
}
//[self.view addSubview:SlickEatsView];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
/*-(IBAction)getStartedButton_Clicked:(id)sender
{
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
self.activityIndicator.frame = CGRectMake(135, 150, 40, 40);
[self.view addSubview:activityIndicator];
if (self.activityIndicator.isAnimating == NO)
{
[self.activityIndicator startAnimating];
}
/*if(locationManager == nil)
{
[[self locationManager] startUpdatingLocation];
}*/
/*SlickEatsWelcomePage *welcomePage = [[SlickEatsWelcomePage alloc]initWithNibName:#"SlickEatsWelcomePage" bundle:nil];
appDelegate = (SlickEatsAppDelegate *)[[UIApplication sharedApplication]delegate];
xmlParserShowTodaysOffer = [XMLParserShowTodaysOffer alloc];
xmlParserShowTodaysOffer.currentCity = appDelegate.myCurrentCity;
xmlParserShowTodaysOffer.currentLatitude = appDelegate.myCurrentLatitude;
xmlParserShowTodaysOffer.currentLongitude = appDelegate.myCurrentLongitude;
[xmlParserShowTodaysOffer initXMLParser];
[xmlParserShowTodaysOffer release];
[self.navigationController pushViewController:welcomePage animated:YES];
[welcomePage release];
[activityIndicator removeFromSuperview];
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"9763912503"]];
}*/
- (CLLocationManager *)locationManager {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; // 100 m
[locationManager startUpdatingLocation];
return locationManager;
}
#pragma mark -
#pragma mark CLLocationManagerDelegate Methods
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
appDelegate = (SlickEatsAppDelegate *)[[UIApplication sharedApplication]delegate];
int degrees = newLocation.coordinate.latitude;
double decimal = fabs(newLocation.coordinate.latitude - degrees);
int minutes = decimal * 60;
double seconds = decimal * 3600 - minutes * 60;
NSString *lat = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
//latLabel.text = lat;
NSLog(#"Current..Latitude::%#",lat);
NSString *CurrentLatitude = [NSString stringWithFormat:#"%lf",newLocation.coordinate.latitude];
NSLog(#"Current..Latitude::%#",CurrentLatitude);
//self.myCurrentLatitude=lat;
degrees = newLocation.coordinate.longitude;
decimal = fabs(newLocation.coordinate.longitude - degrees);
minutes = decimal * 60;
seconds = decimal * 3600 - minutes * 60;
NSString *longt = [NSString stringWithFormat:#"%d° %d' %1.4f\"", degrees, minutes, seconds];
//longLabel.text = longt;
NSLog(#"Current..Longitude::%#",longt);
NSString *CurrentLongitude = [NSString stringWithFormat:#"%lf",newLocation.coordinate.longitude];
NSLog(#"Current..Longitude::%#",CurrentLongitude);
appDelegate.myCurrentLatitude = CurrentLatitude;
appDelegate.myCurrentLongitude = CurrentLongitude;
MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
geoCoder.delegate = self;
[geoCoder start];
}
// this delegate is called when the reverseGeocoder finds a placemark
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
MKPlacemark * myPlacemark = placemark;
// with the placemark you can now retrieve the city name
NSString *city =[ myPlacemark.addressDictionary objectForKey:(NSString*) kABPersonAddressCityKey];
// NSString *city = (NSString *)[myPlacemark.locality length];
NSLog(#"Current Add::%#",city);
appDelegate.myCurrentCity = city;
//[self sendLocation];
}
// this delegate is called when the reversegeocoder fails to find a placemark
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
NSLog(#"reverseGeocoder:%# didFailWithError:%#", geocoder, error);
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"error%#",error);
switch([error code])
{
case kCLErrorNetwork: // general, network-related error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"please check your network connection or that you are not in airplane mode" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
break;
case kCLErrorDenied:{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"user has denied to use current Location " delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
break;
default:
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"unknown network error" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
break;
}
}
-(void)sendLocation
{
NSLog(#"in Send Location..");
SlickEatsWelcomePage *welcomePage = [[SlickEatsWelcomePage alloc]initWithNibName:#"SlickEatsWelcomePage" bundle:nil];
appDelegate = (SlickEatsAppDelegate *)[[UIApplication sharedApplication]delegate];
xmlParserShowTodaysOffer = [XMLParserShowTodaysOffer alloc];
xmlParserShowTodaysOffer.currentCity = appDelegate.myCurrentCity;
xmlParserShowTodaysOffer.currentLatitude = appDelegate.myCurrentLatitude;
xmlParserShowTodaysOffer.currentLongitude = appDelegate.myCurrentLongitude;
[xmlParserShowTodaysOffer initXMLParser];
[xmlParserShowTodaysOffer release];
[self.navigationController pushViewController:welcomePage animated:YES];
[welcomePage release];
//[locationManager release];
}
-(IBAction)workButton_clicked:(id)sender
{
/*activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
self.activityIndicator.frame = CGRectMake(135, 150, 40, 40);
[self.splashLogoImageView addSubview:activityIndicator];
if (self.activityIndicator.isAnimating == NO)
{
[self.activityIndicator startAnimating];
}*/
SlickEatsSplashScreen *intro = [[SlickEatsSplashScreen alloc]initWithNibName:#"SlickEatsSplashScreen" bundle:nil];
[self.navigationController pushViewController:intro animated:YES];
[intro release];
//[activityIndicator removeFromSuperview];
}
- (void)connectedToNetwork {
BOOL aflag= ([NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.google.co.in/"]]!=NULL)?YES:NO;
if (!aflag) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Sorry!....You are not connected to network "
delegate:self cancelButtonTitle:#"Exit" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
[workButton release];
[howItWorkImageView release];
[splashLogoImageView release];
[getStartedButton release];
[locationManager release];
}
#end
I suspect that you are requesting GPS-like accuracy when the GPS chip isn't getting any signals due to the high rise buildings:
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; // 100 m
Try commenting out the above statement and test it out in the field -- see how accurate the coordinates that you get.
Do you have a data connection? I've heard that it's sometimes tough to get a connection at all in Manhattan on certain networks, due to both the buildings and an overloaded network. If you're not getting data, it's going to be tough to get a fix.