ios - How to declare URLDecode? - iphone

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:&regexError];
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:&regexError];
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.

Related

Separate words from a NSString which are preceded by a hashtag

I have a NSString, for example:
"Had a #great time at the #party last night."
I want to separate this into an array, as so:
"Had a "
"#great"
" time at the "
"#party"
" last night."
How could i do this?
NSString *str = #"Had a #great time at the #party last night.";
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSArray *array = [str componentsSeparatedByString:#"#"];
NSMutableString *retStr= [[NSMutableString alloc] initWithString:[array objectAtIndex:0]];
[arr addObject:retStr];
for(int i=1 ; i<[array count];i++)
{
NSArray *array1 = [[array objectAtIndex:i] componentsSeparatedByString:#" "];
{
NSMutableString *retStr= [[NSMutableString alloc]init];
for (int i = 0;i< [array1 count]; i++)
{
if(i==0)
{
[retStr appendFormat:#" #%# ",[array1 objectAtIndex:i]];
[arr addObject:retStr];
retStr= [[NSMutableString alloc]init];
}
else
{
[retStr appendFormat:#"%# ",[array1 objectAtIndex:i]];
}
}
[arr addObject:retStr];
}
}
NSLog(#"%#",arr);
You will get the corect output as you want
try like this it'l helps you,
NSString *str=#"how are #you #friend";
NSArray *arr=[str componentsSeparatedByString:#" "];
NSPredicate *p = [NSPredicate predicateWithFormat:#"not SELF contains '#'"];
NSArray *b = [arr filteredArrayUsingPredicate:p];
NSLog(#"%#",b);
above predicate will returns the words which are not containg '#' symbol
NSPredicate *p = [NSPredicate predicateWithFormat:#"not SELF like '#*'"];
it'l returns the words which are not started with the letter '#'
O/P:-
(
how,
are
)
EDIT:-
NSString *str=#"how are #you #friend";
NSArray *arr=[str componentsSeparatedByString:#"#"];
NSMutableArray *result=[[NSMutableArray alloc]initWithObjects:[arr objectAtIndex:0], nil];
for(int i=1;i<[arr count];i++){
[result addObject:[NSString stringWithFormat:#"#%#",[arr objectAtIndex:i]]];
}
NSLog(#"%#",result);
O/P:-
(
"how are ",
"#you ",
"#friend"
)
Try to use this regexp: (#.+?\\b)|(.+?(?=#|$))
It find words which begins with hashtag and subsequences which ends with hashtag
NSString * string = #"Had a #great time at the #party last night.";
NSError * error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"((#.+?\\b)|(.+?(?=#|$)))"
options:0
error:&error];
NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult* match in matches ) {
NSLog(#"%#", [string substringWithRange:[match range]]);
}
Output:
2013-04-29 16:57:51.688 Had a
2013-04-29 16:57:51.689 #great
2013-04-29 16:57:51.690 time at the
2013-04-29 16:57:51.691 #party
2013-04-29 16:57:51.692 last night.
If you want to do it efficiently in a single pass on the string you can try something like (scratch code - test for bugs/boundary cases etc...):
int main (int argc, const char * argv[])
{
NSString *msg = #"Had a #great time at the #party last night.";
Boolean inTag = NO;
NSMutableArray *segments = [[NSMutableArray alloc] init];
NSUInteger idx = 0;
NSUInteger i=0;
for (; i < [msg length]; i++)
{
unichar ch = [msg characterAtIndex:i];
if (inTag && ch == ' ')
{
[segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx)]];
idx = i;
inTag = NO;
}
if (ch == '#')
{
[segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx)]];
idx = i;
inTag = YES;
}
}
if (i > idx)
{
[segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx - 1)]];
}
for(NSString *seg in segments)
{
NSLog(#"%#", seg);
}
}
This outputs:
2013-04-29 08:34:34.984 Craplet[95591:707] Had a
2013-04-29 08:34:34.986 Craplet[95591:707] #great
2013-04-29 08:34:34.986 Craplet[95591:707] time at the
2013-04-29 08:34:34.987 Craplet[95591:707] #party
2013-04-29 08:34:34.987 Craplet[95591:707] last night
Try this:
for (int i=0;i<[YourArray count];i++) {
NSString * mystr=[YourArray objectAtIndex:i];
NSString *temp=[mystr substringToIndex:1];
if (![temp isEqualToString:#"#"]) {
//add your string in new array and use this arry.....
}
}
try this code
for (int i=0;i<[YourArray count];i++) {
NSString * str=[YourArray objectAtIndex:i];
NSString *myString=[str substringToIndex:1];
NSString *stringfinal = [myString
stringByReplacingOccurrencesOfString:#"#" withString:#""];
}
Try using regular expressions. With this code you'll be able to extract the hashtags:
NSString * string = #"Had a #great time at the #party last night.";
NSError * error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"((?:#){1}[\\w\\d]{1,140})" options:0 error:&error];
NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for ( NSTextCheckingResult* match in matches )
{
NSString * hashtag = [string substringWithRange:[match range]];
NSLog(#"match: %#", hashtag);
}
With this, you'll be able to build up the array result you're looking for.
Try
NSString *string = #"Had a #great time at the #party last night.";
NSArray *components = [string componentsSeparatedByString:#" "];
NSMutableArray *formattedArray = [NSMutableArray array];
NSMutableString *mutableString = [NSMutableString string];
for (NSString *string in components)
{
if (![string hasPrefix:#"#"]){
if (!mutableString){
mutableString = [NSMutableString string];
}
[mutableString appendFormat:#" %#",string];
}else{
if (mutableString) {
[formattedArray addObject:mutableString];
mutableString = nil;
}
[formattedArray addObject:string];
}
}
if (mutableString) {
[formattedArray addObject:mutableString];
}
NSLog(#"%#",formattedArray);
EDIT :
(
" Had a",
"#great",
" time at the",
"#party",
" last night."
)
One-pass solution with NSScanner
NSString *string = #"Had a #great time at the #party last night.";
NSMutableArray *array = [#[] mutableCopy];
NSScanner *scanner = [NSScanner scannerWithString:string];
while (![scanner isAtEnd]) {
NSString *s;
[scanner scanUpToString:#"#" intoString:&s];
if(s) [array addObject:s];
s = nil;
[scanner scanUpToString:#" " intoString:&s];
if(s) [array addObject:s];
}
result:
(
"Had a ",
"#great",
"time at the ",
"#party",
"last night."
)
if you want to preserve the leading whitespace, alter it slightly to
NSString *string = #"Had a #great time at the #party last night.";
NSMutableArray *array = [#[] mutableCopy];
NSScanner *scanner = [NSScanner scannerWithString:string];
BOOL firstSegment = YES;
while (![scanner isAtEnd]) {
NSString *s;
[scanner scanUpToString:#"#" intoString:&s];
if(s) [array addObject: (!firstSegment) ? [#" " stringByAppendingString:s] : s];
s = nil;
[scanner scanUpToString:#" " intoString:&s];
if(s) [array addObject:s];
firstSegment = NO;
}
result:
(
"Had a ",
"#great",
" time at the ",
"#party",
" last night."
)

ios - How to use URLDecode?

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:&regexError];
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:&regexError];
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.

How to extract a number from a string using NSRegularExpression

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.

nsstring replace string in range

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

Subtracting 2 strings

I have a string say for example #"012" and I have another string #"02". How can I extract the difference of the 2 strings in iPhone Objective-C. I just need to remove the existence of the characters in the 2nd string from the first string.The answer would be "1".
Even shorter:
NSString* s1 = #"012";
NSString* s2 = #"02";
NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString:s2];
NSString * final = [[s1 componentsSeparatedByCharactersInSet:set] componentsJoinedByString:#""];
NSLog(#"Final: %#", final);
This preserves the order of the characters in the original string.
You could do something like this;
NSString *s1 = #"012";
NSString *s2 = #"02";
NSCharacterSet *charactersToRemove;
charactersToRemove = [NSCharacterSet characterSetWithCharactersInString:s2];
NSMutableString *result = [NSMutableString stringWithCapacity:[s1 length]];
for (NSUInteger i = 0; i < [s1 length]; i++) {
unichar c = [s1 characterAtIndex:i];
if (![charactersToRemove characterIsMember:c]) {
[result appendFormat:#"%C", c];
}
}
// if memory is an issue:
result = [[result copy] autorelease];
Disclaimer: I typed this into the browser, and haven't tested any of this.
You're trying to do a set operation, so use sets.
{
NSString* s1 = #"012";
NSString* s2 = #"02";
NSMutableSet* set1 = [NSMutableSet set];
NSMutableSet* set2 = [NSMutableSet set];
for(NSUInteger i = 0; i < [s1 length]; ++i)
{
[set1 addObject:[s1 substringWithRange:NSMakeRange(i, 1)]];
}
for(NSUInteger i = 0; i < [s2 length]; ++i)
{
[set2 addObject:[s2 substringWithRange:NSMakeRange(i, 1)]];
}
[set1 minusSet:set2];
NSLog(#"set1: %#", set1);
// To get a single NSString back from the set:
NSMutableString* result = [NSMutableString string];
for(NSString* piece in set1)
{
[result appendString:piece];
}
NSLog(#"result: %#", result);
}
I simply used "componentsSeparatedByString"
NSString *s1 = #"abc";
NSString *s2 = #"abcdef";
//s2 - s1
NSString * final = [[s2 componentsSeparatedByString:s1] componentsJoinedByString:#""];