Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
HTTP Link header parser (http://tools.ietf.org/html/rfc5988)
License: BSD
NSDictionary *links = KFParseRelativeLinks(@"<http://github.com?page=2>; rel=next");
NSURL *nextURL = links[@"next"];
*/
NSDictionary *KFParseRelativeLinks(NSString *header) {
NSMutableDictionary *links = [[NSMutableDictionary alloc] init];
for (NSString *source in [header componentsSeparatedByString:@","]) {
NSRange range = [source rangeOfString:@";"];
if (range.location == NSNotFound) {
continue;
}
NSString *urlString = [source substringToIndex:range.location];
NSCharacterSet *urlCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"<> "];
urlString = [urlString stringByTrimmingCharactersInSet:urlCharacterSet];
NSURL *URL = [[NSURL alloc] initWithString:urlString];
if (URL == nil) {
continue;
}
NSString *params = [source substringFromIndex:range.location + 1];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
for (NSString *parameter in [params componentsSeparatedByString:@";"]) {
NSRange range = [parameter rangeOfString:@"="];
if (range.location == NSNotFound) {
continue;
}
NSString *key = [[parameter substringToIndex:range.location] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *value = [[parameter substringFromIndex:range.location + 1] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\"' "]];
parameters[key] = value;
}
NSString *rel = parameters[@"rel"];
if (rel) {
links[rel] = URL;
}
}
return [links copy];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.