Skip to content

Instantly share code, notes, and snippets.

@joemasilotti
Last active March 26, 2020 09:35
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joemasilotti/09fe1f247a3da1c782dd to your computer and use it in GitHub Desktop.
Save joemasilotti/09fe1f247a3da1c782dd to your computer and use it in GitHub Desktop.
Building NSURL Queries with NSURLQueryItems and NSURLComponents
NSString *urlString = @"api.twitter.com/1.1/statuses/user_timeline.json?screen_name=joemasilotti";
NSURL *url = [NSURL URLWithString:urlString];
urlString = [urlString stringByAppendingString:@"&include_rts=true"];
url = [NSURL URLWithString:urlString];
NSString *screenName = @"joemasilotti";
NSString *includeRTs = @"true";
urlString = [NSString stringWithFormat:@"api.twitter.com/1.1/statuses/user_timeline.json?screen_name=%@&include_rts=%@", screenName, includeRTs];
url = [NSURL URLWithString:urlString];
NSURLComponents *components = [[NSURLComponents alloc] init];
components.scheme = @"http";
components.host = @"www.api.twitter.com";
components.path = @"/1.1/statuses/user_timeline.json";
components.query = @"screen_name=joemasilotti&include_rts=true";
url = components.URL;
NSLog(@"%@", components.queryItems);
/*
(
"<NSURLQueryItem 0x7fbdbb4281b0> {name = screen_name, value = joemasilotti}",
"<NSURLQueryItem 0x7fbdbb428250> {name = include_rts, value = true}"
)
*/
NSURLQueryItem *screenNameItem = [NSURLQueryItem queryItemWithName:@"screen_name"
value:@"joemasilotti"];
NSURLQueryItem *includeRTsItem = [NSURLQueryItem queryItemWithName:@"include_rts"
value:@"true"];
components.queryItems = @[ screenNameItem, includeRTsItem ];
NSLog(@"%@", components.URL);
for (NSURLQueryItem *item in components.queryItems) {
if ([item.name isEqualToString:@"screen_name"]) {
if ([item.value isEqualToString:@"joemasilotti"]) {
return YES;
}
}
return NO;
}
NSURLQueryItem *item = [NSURLQueryItem queryItemWithName:@"screen_name"
value:@"joemasilotti"];
[components.queryItems containsObject:item] should be_truthy;
@singhamit089
Copy link

While I tried your method, I got following exception on line no 31

-[__NSCFNumber stringByAddingPercentEncodingWithAllowedCharacters:]: unrecognized selector sent to instance 0xb0000000000000a2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment