I'm trying to get access token,I'm following this link http://www.stevesaxon.me/posts/2011/window-external-notify-in-ios-uiwebview/ to get that,but I'm getting some problem when decode URL.Please go through that link.
- (NSDictionary*)parsePairs:(NSString*)urlStr
{
NSRange r = [urlStr rangeOfString:#"="];
if(r.length == 0)
{
return nil;
}
//Here Program received signal stopped
NSString* token = [[urlStr substringFromIndex:r.location + 1 ] URLDecode];
NSCharacterSet* objectMarkers;
objectMarkers = [NSCharacterSet characterSetWithCharactersInString:#"{}"];
token = [token stringByTrimmingCharactersInSet:objectMarkers];
NSError* regexError;
NSMutableDictionary* pairs = [NSMutableDictionary dictionaryWithCapacity:10];
NSRegularExpression* regex;
regex = [NSRegularExpression regularExpressionWithPattern:#"\"([^\"]*)\":\"([^\"]*)\""
options:0
error:®exError];
NSArray* matches = [regex matchesInString:token
options:0
range:NSMakeRange(0, token.length)];
for(NSTextCheckingResult* result in matches)
{
for(int n = 1; n < [result numberOfRanges]; n += 2)
{
NSRange r = [result rangeAtIndex:n];
if(r.length > 0)
{
NSString* name = [token substringWithRange:r];
r = [result rangeAtIndex:n + 1];
if(r.length > 0)
{
NSString* value = [token substringWithRange:r];
[pairs setObject:value forKey:name];
}
}
}
}
regex = [NSRegularExpression regularExpressionWithPattern:#"\"([^\"]*)\":([0-9]*)"
options:0
error:®exError];
matches = [regex matchesInString:token
options:0
range:NSMakeRange(0, token.length)];
for(NSTextCheckingResult* result in matches)
{
for(int n = 1; n < [result numberOfRanges]; n += 2)
{
NSRange r = [result rangeAtIndex:n];
if(r.length > 0)
{
NSString* name = [token substringWithRange:r];
r = [result rangeAtIndex:n + 1];
if(r.length > 0)
{
NSString* value = [token substringWithRange:r];
NSNumber* number = [NSNumber numberWithInt:[value intValue]];
[pairs setObject:number forKey:name];
}
}
}
}
return pairs;
}
Any ideas? Thanks in advance.
Related
I'm trying to get access token,when I decode URL it's getting an error,I think am declaring wrong here.How to declare URLDecode to get access token?
in .h file
#interface NSString (URLDecode)
-(NSString *)URLDecode;
#end
in .m file
-(NSString *)URLDecode
{
NSString *result = [(NSString*)self stringByReplacingOccurrencesOfString:#"+" withString:#" "];
result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return result;
}
- (NSDictionary*)parsePairs:(NSString*)urlStr
{
NSRange r = [urlStr rangeOfString:#"="];
if(r.length == 0)
{
return nil;
}
//Here I'm getting an error
NSString* token = [[urlStr substringFromIndex:r.location + 1 ] URLDecode];
NSCharacterSet* objectMarkers;
objectMarkers = [NSCharacterSet characterSetWithCharactersInString:#"{}"];
token = [token stringByTrimmingCharactersInSet:objectMarkers];
NSError* regexError;
NSMutableDictionary* pairs = [NSMutableDictionary dictionaryWithCapacity:10];
NSRegularExpression* regex;
regex = [NSRegularExpression regularExpressionWithPattern:#"\"([^\"]*)\":\"([^\"]*)\""
options:0
error:®exError];
NSArray* matches = [regex matchesInString:token
options:0
range:NSMakeRange(0, token.length)];
for(NSTextCheckingResult* result in matches)
{
for(int n = 1; n < [result numberOfRanges]; n += 2)
{
NSRange r = [result rangeAtIndex:n];
if(r.length > 0)
{
NSString* name = [token substringWithRange:r];
r = [result rangeAtIndex:n + 1];
if(r.length > 0)
{
NSString* value = [token substringWithRange:r];
[pairs setObject:value forKey:name];
}
}
}
}
regex = [NSRegularExpression regularExpressionWithPattern:#"\"([^\"]*)\":([0-9]*)"
options:0
error:®exError];
matches = [regex matchesInString:token
options:0
range:NSMakeRange(0, token.length)];
for(NSTextCheckingResult* result in matches)
{
for(int n = 1; n < [result numberOfRanges]; n += 2)
{
NSRange r = [result rangeAtIndex:n];
if(r.length > 0)
{
NSString* name = [token substringWithRange:r];
r = [result rangeAtIndex:n + 1];
if(r.length > 0)
{
NSString* value = [token substringWithRange:r];
NSNumber* number = [NSNumber numberWithInt:[value intValue]];
[pairs setObject:number forKey:name];
}
}
}
}
return pairs;
}
Any ideas?
You need to make a cetgory of NSString in your Xcode project as :
1.
Then do as :
Then when you click Next button a cetgory will be created of NSString . Then use add code in that. And then Import this category in your class as :
#import "NSString+URLDecode.h"
and then call method declared in category over NSString as
NSString *decodedUrlStr = [urlStr URLDecode];
Hope it helps you.
I want to extract the number 81698 from the string below, however I am running into some difficulties.
Here is my code.
NSString *content = #"... list.vars.results_thpp = 32;
list.vars.results_count = 81698;
list.vars.results_board = '12'; ...";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"results_count.*[0-9*];"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:content
options:0
range:NSMakeRange(0, [content length])
withTemplate:#"$1"];
The output is this
... list.vars.results_thpp = 32;
list.vars.
list.vars.results_board = '12'; ...
But I just want 81698
What am I doing wrong?
NSString *content = #"... list.vars.results_thpp = 32;list.vars.results_count = 81698;list.vars.results_board = '12'; ...";
NSString *param = nil;
NSRange start = [content rangeOfString:#"list.vars.results_count = "];
if (start.location != NSNotFound) {
param = [content substringFromIndex:start.location + start.length];
NSRange end = [param rangeOfString:#";"];
if (end.location != NSNotFound) {
param = [param substringToIndex:end.location];
}
}
NSLog(#"param:%#", param);
I think it will be helpful to you.
I am doing work with map and location. I want to have road map from one location to another location. I am providing latitude and longitude of both the location(destination and source). So please help me to have this map.
I read about Google map api but I didn't find perfect answer.
Use below URL of google map API to find the road map route between two locations
http://maps.google.com/?saddr=STARTINGADDRESS&daddr=DESTINATIONADDRESS
First you have to take the directions from Google. Like this:
NSError *error = nil;
NSString *directionsInJSON = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=true",start.coordinate.latitude , start.coordinate.longitude , destination.coordinate.latitude, destination.coordinate.longitude]]encoding:NSUTF8StringEncoding error:&error];
After that , parse the JSON you got above:
if (error == nil)
{
NSError *JSONError = nil;
SBJsonParser *JSONParser = [[SBJsonParser alloc] init];
id directions = [JSONParser objectWithString:directionsInJSON error:&JSONError];
if (JSONError == nil)
{
directions = (NSDictionary*)directions;
NSString *status = [directions objectForKey:#"status"];
if ([status isEqualToString:#"OK"])
{
NSArray *routes = [directions objectForKey:#"routes"];
NSDictionary *route = [routes objectAtIndex:0];
NSDictionary *polylineOverview = [route objectForKey:#"overview_polyline"];
NSString *polylinePoints = [polylineOverview objectForKey:#"points"];
NSArray *decodedPolyline = [self decodePolyLine:polylinePoints];
[self loadRouteWithPoints:decodedPolyline];
}
else
{
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"No routes found" message:#"Sorry , we couldn't find any routes between you two." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil] autorelease];
[alert show];
}
}
}
else
{
NSLog(#"error: %#",error.description);
}
Now you need these methods:
-(void) loadRouteWithPoints:(NSArray *) routes
{
CLLocationCoordinate2D coords[[routes count]];
for(int i = 0; i < routes.count; i++)
{
CLLocation* loc = (CLLocation*)[routes objectAtIndex:i];//[NSKeyedUnarchiver unarchiveObjectWithData:[routes objectAtIndex:i]];
CLLocationCoordinate2D c;
c.latitude = loc.coordinate.latitude;
c.longitude = loc.coordinate.longitude;
coords[i] = c;
}
MKPolyline *line = [[MKPolyline polylineWithCoordinates:(CLLocationCoordinate2D*)coords count:[routes count]] retain];
[self.mapsView addOverlay:line];
}
And:
- (NSMutableArray *)decodePolyLine: (NSString *)encoded
{
NSInteger len = [encoded length];
NSInteger index = 0;
NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
NSInteger lat=0;
NSInteger lng=0;
while (index < len)
{
NSInteger b;
NSInteger shift = 0;
NSInteger result = 0;
do
{
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do
{
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
NSNumber *latitude = [[[NSNumber alloc] initWithFloat:lat * 1e-5] autorelease];
NSNumber *longitude = [[[NSNumber alloc] initWithFloat:lng * 1e-5] autorelease];
CLLocation *loc = [[[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] autorelease];
[array addObject:loc];
}
return array;
}
Voila!
Cheers!
I have a string with certain pattern. I need to search for the pattern and replace the string inside that pattern. For eg :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSString *result = nil;
// Determine "{" location
NSRange startRange = [string rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [string length] - endRange.location;
endRange = [string rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
result = [string substringWithRange:startRange];
}
}
Here I am able to extract the first substring that is between "{ }" ie - "Hello" but I also need to continue the check and want to extract other strings.
Try this one:
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
//NSString *result = nil;
// Determine "{" location
NSArray *array=[string componentsSeparatedByString:#"{"];
for(NSString *str in array){
NSString *newString=[[str componentsSeparatedByString:#"}"] objectAtIndex:0];
NSLog(#"%#",newString);
}
try this :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSMutableString *result = [[NSMutableString alloc] init];
NSArray *tempArray = [[string componentsSeparatedByString:#" "] mutableCopy];
for (int i=0; i < [tempArray count]; i++)
{
NSString *tempStr = [tempArray objectAtIndex:i];
NSRange startRange = [tempStr rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [tempStr length] - endRange.location;
endRange = [tempStr rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
//result = [tempStr substringWithRange:startRange];
[result appendString:[NSString stringWithFormat:#"%# ",[tempStr substringWithRange:startRange]]];
NSLog(#"%# ",result);
}
}
}
Take care for release for tempArray and result
I happen to have this code lying around. I think it does exactly what you want. I implemented it as a category on NSString. You use it like this:
NSString *template = #"{Hello} ({World}) ({How}) etc etc";
NSDictionary *vars = [NSDictionary dictionaryWithObjectsAndKeys:
#"Bonjour", #"Hello",
#"Planet Earth", #"World",
#"Como", #"How",
// etc.
nil];
NSString *expandedString = [template stringByExpandingTemplateWithVariables:vars];
// expandedString is #"Bonjour (Planet Earth) (Como) etc etc"
Here's the code.
File NSString+TemplateExpansion.h
#import <Foundation/Foundation.h>
#interface NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary;
#end
File NSString+TemplateExpansion.m
#import "NSString+TemplateExpansion.h"
#implementation NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary
{
NSUInteger myLength = self.length;
NSMutableString *result = [NSMutableString stringWithCapacity:myLength];
NSRange remainingRange = NSMakeRange(0, myLength);
while (remainingRange.length > 0) {
NSRange leftBraceRange = [self rangeOfString:#"{" options:0 range:remainingRange];
if (leftBraceRange.location == NSNotFound)
break;
NSRange afterLeftBraceRange = NSMakeRange(NSMaxRange(leftBraceRange), myLength - NSMaxRange(leftBraceRange));
NSRange rightBraceRange = [self rangeOfString:#"}" options:0 range:afterLeftBraceRange];
if (rightBraceRange.location == NSNotFound)
break;
NSRange beforeLeftBraceRange = NSMakeRange(remainingRange.location, leftBraceRange.location - remainingRange.location);
[result appendString:[self substringWithRange:beforeLeftBraceRange]];
remainingRange = NSMakeRange(NSMaxRange(rightBraceRange), myLength - NSMaxRange(rightBraceRange));
NSRange keyRange = NSMakeRange(NSMaxRange(leftBraceRange), rightBraceRange.location - NSMaxRange(leftBraceRange));
NSString *key = [self substringWithRange:keyRange];
NSString *value = [dictionary objectForKey:key];
if (value)
[result appendString:value];
}
[result appendString:[self substringWithRange:remainingRange]];
return result;
}
#end
Is there a way where i could get the driving distance to a particular geo-cordinate ? I am aware that i have to use http://maps.googleapis.com/maps/api/directions/output?parameters and get a JSON output to get the results.
Is there a tutorial that explains how to get this done? or any sample code where i start on?
You may try the following. This code fetches all directions (even the alternate ones) returned by Google Directions Services. You can get the distance in step 2 (parsing response)
Step 1: Enter the From and To Locations
NSMutableString *googleURL = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%#&sensor=true&alternatives=true", searchFrom.text, searchTo.text]];
NSURL *url = [NSURL URLWithString:googleURL];
[googleURL release];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
request = nil;
responseData = [[NSMutableData alloc] init];
Step 2: When you get the response of the query made, parse the result
- (id)parseResponseWithDictionary:(NSDictionary *)dictResponse {
if ([[dictResponse objectForKey:#"status"] isEqualToString:kGoogleDirectionsStatusOK]) {
NSArray *listRoutes = (NSArray *)[dictResponse objectForKey:#"routes"];
NSMutableString *result = nil;
NSMutableArray *listPolylines = nil;
for (NSDictionary *dictRouteValues in listRoutes) {
NSDictionary *dictPolyline = [dictRouteValues objectForKey:#"overview_polyline"];
if (!result) {
result = [[NSMutableString alloc] init];
}
[result appendString:[dictPolyline objectForKey:#"points"]];
if (!listPolylines) {
listPolylines = [[NSMutableArray alloc] init];
}
[listPolylines addObject:result];
[result release];
result = nil;
}
return [listPolylines autorelease];
}
else {
NSString *error = #"No result found. Please check start and end location again!";
return error;
}
return nil;
}
Step 3: Decode each polyline in the polyline list. This will give the path coordinates.
-(NSMutableArray *)decodePolyLine:(NSMutableString *)encoded {
[encoded replaceOccurrencesOfString:#"\\\\" withString:#"\\"
options:NSLiteralSearch
range:NSMakeRange(0, [encoded length])];
NSInteger len = [encoded length];
NSInteger index = 0;
NSMutableArray *listCoordinates = [[[NSMutableArray alloc] init] autorelease];
NSInteger lat=0;
NSInteger lng=0;
while (index < len) {
NSInteger b;
NSInteger shift = 0;
NSInteger result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5];
NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];
//CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
[listCoordinates addObject:[NSString stringWithFormat:#"%f,%f", [latitude floatValue], [longitude floatValue]]];
//[loc release];
[latitude release];
[longitude release];
}
return listCoordinates;
}
this newer tutorial/sample code using CoreLocation and MapKit helped me a bunch.