PageRenderTime 45ms CodeModel.GetById 1ms app.highlight 41ms RepoModel.GetById 1ms app.codeStats 0ms

/MapView/Map/RMCloudMadeMapSource.m

http://github.com/route-me/route-me
Objective C | 179 lines | 132 code | 19 blank | 28 comment | 13 complexity | 9bccce7d965d8c9bae6edb4cea36aff2 MD5 | raw file
  1//
  2//  RMCloudMadeMapSource.m
  3//  MapView
  4//
  5// Copyright (c) 2008-2009, Cloudmade
  6// All rights reserved.
  7//
  8// Redistribution and use in source and binary forms, with or without
  9// modification, are permitted provided that the following conditions are met:
 10//
 11// * Redistributions of source code must retain the above copyright notice, this
 12//   list of conditions and the following disclaimer.
 13// * Redistributions in binary form must reproduce the above copyright notice,
 14//   this list of conditions and the following disclaimer in the documentation
 15//   and/or other materials provided with the distribution.
 16//
 17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 18// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 19// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 20// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 21// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 22// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 23// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 24// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 25// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 26// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 27// POSSIBILITY OF SUCH DAMAGE.
 28
 29#import "RMCloudMadeMapSource.h"
 30
 31@implementation RMCloudMadeMapSource
 32
 33#define kDefaultCloudMadeStyleNumber 7
 34#define kDefaultCloudMadeSize 256
 35#define kTokenFileName @"accessToken"
 36NSString * const RMCloudMadeAccessTokenRequestFailed = @"RMCloudMadeAccessTokenRequestFailed"; 
 37#define CMTokenAuthorizationServer  @"http://auth.cloudmade.com" 
 38
 39
 40+ (NSString*)pathForSavedAccessToken
 41{
 42	NSArray *paths;
 43	paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 44	if ([paths count] > 0) // Should only be one...
 45	{
 46		NSString *cachePath = [paths objectAtIndex:0];
 47		return [cachePath stringByAppendingPathComponent:kTokenFileName];
 48	}
 49	return nil;
 50}
 51
 52-(BOOL) readTokenFromFile
 53{
 54	NSString* pathToSavedAccessToken = [RMCloudMadeMapSource pathForSavedAccessToken];
 55	if([[NSFileManager defaultManager] fileExistsAtPath:pathToSavedAccessToken])
 56	{
 57		NSError* error;
 58		accessToken = [[NSString alloc] initWithContentsOfFile:pathToSavedAccessToken encoding:NSASCIIStringEncoding error:&error];
 59		if(!accessToken)
 60		{
 61			RMLog(@"can't read file %@ %@\n",pathToSavedAccessToken,error.localizedDescription);
 62			[[NSFileManager defaultManager] removeItemAtPath:pathToSavedAccessToken error:nil];
 63			return FALSE;
 64		}
 65		return TRUE;
 66	}
 67	return FALSE;
 68}
 69
 70-(void) requestToken
 71{
 72	
 73	if([self readTokenFromFile])
 74			return;
 75	
 76	NSString* url = [NSString stringWithFormat:@"%@/token/%@?userid=%u",CMTokenAuthorizationServer,accessKey,
 77					[[UIDevice currentDevice].uniqueIdentifier hash]];
 78
 79	
 80	NSData* data = nil;
 81	RMLog(@"%s, url = %@\n",__FUNCTION__,url);
 82	NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
 83											  cachePolicy:NSURLRequestUseProtocolCachePolicy
 84										  timeoutInterval:5.0];
 85	[ theRequest setHTTPMethod: @"POST" ];
 86
 87	NSURLResponse* response;
 88	NSError*       error = nil; 
 89	BOOL done = FALSE;
 90	int attempt = 0;
 91	do
 92	{
 93		data = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
 94		if(data && [(NSHTTPURLResponse*)response statusCode] == 200)
 95		{
 96			NSString* pathToSavedAccessToken = [RMCloudMadeMapSource pathForSavedAccessToken];
 97			accessToken = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
 98			[accessToken writeToFile:pathToSavedAccessToken atomically:YES encoding:NSASCIIStringEncoding error:nil];
 99			done = TRUE;
100		}
101		else
102		{
103			if([(NSHTTPURLResponse*)response statusCode] == 403 && !attempt)
104			{
105				RMLog(@"Token wasn't obtained.Response code = %d\n",[(NSHTTPURLResponse*)response statusCode]);
106				attempt++;
107			}
108			else
109			{
110				RMLog(@"Token wasn't obtained %@\n",error.localizedDescription);
111				[[NSNotificationCenter defaultCenter] postNotificationName:RMCloudMadeAccessTokenRequestFailed object:error];
112				done = TRUE;
113			}
114			
115		}
116	}
117	while(!done);
118}
119
120- (id) init
121{
122	return [self initWithAccessKey:@""
123					   styleNumber:kDefaultCloudMadeStyleNumber];
124}
125
126/// designated initializer
127- (id) initWithAccessKey:(NSString *)developerAccessKey
128			 styleNumber:(NSUInteger)styleNumber;
129{
130	NSAssert((styleNumber > 0), @"CloudMade style number must be positive");
131	NSAssert(([developerAccessKey length] > 0), @"CloudMade access key must be non-empty");
132	if (self = [super init])
133	{
134		[self setTileSideLength:kDefaultCloudMadeSize];
135		accessKey = developerAccessKey;
136		if (styleNumber > 0)
137			cloudmadeStyleNumber = styleNumber;
138		else
139			cloudmadeStyleNumber = kDefaultCloudMadeStyleNumber;
140	}
141	[self requestToken];
142	return self;
143}
144
145- (NSString*) tileURL: (RMTile) tile
146{
147	NSAssert4(((tile.zoom >= self.minZoom) && (tile.zoom <= self.maxZoom)),
148			  @"%@ tried to retrieve tile with zoomLevel %d, outside source's defined range %f to %f", 
149			  self, tile.zoom, self.minZoom, self.maxZoom);
150	NSAssert(accessToken,@"CloudMade access token must be non-empty");
151	return [NSString stringWithFormat:@"http://tile.cloudmade.com/%@/%d/%d/%d/%d/%d.png?token=%@",
152			accessKey,
153			cloudmadeStyleNumber,
154			kDefaultCloudMadeSize, tile.zoom, tile.x, tile.y,accessToken];
155}
156
157-(NSString*) uniqueTilecacheKey
158{
159	return [NSString stringWithFormat:@"CloudMadeMaps%d", cloudmadeStyleNumber];
160}
161
162-(NSString *)shortName
163{
164	return [NSString stringWithFormat:@"Cloud Made %d", cloudmadeStyleNumber];
165}
166-(NSString *)longDescription
167{
168	return @"CloudMade.com provides high quality renderings of Open Street Map data";
169}
170-(NSString *)shortAttribution
171{
172	return @2009 CloudMade.com";
173}
174-(NSString *)longAttribution
175{
176	return @"Map © CloudMade.com. Map data CCBYSA 2009 OpenStreetMap.org contributors.";
177}
178
179@end