How to extract and remove schema name from NSURL?

What is the correct way to retrieve and delete the schema name and :// from NSURL ?

For instance:

  note://Hello -> @"Hello" calc://3+4/5 -> @"3+4/5" 

So

 NSString *scheme = @"note://"; NSString *path = @"Hello"; 

for later use in:

 [[NSNotificationCenter defaultCenter] postNotificationName:scheme object:path]; 
+6
source share
3 answers

You can look at it like this (mostly untested code, but you get the idea):

 - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { NSLog(@"scheme: %@", [url scheme]); NSLog(@"url: %@", url); NSLog(@"query: %@", [url query]); NSLog(@"host: %@", [url host]); NSLog(@"path: %@", [url path]); NSDictionary * dict = [self parseQueryString:[url query]]; NSLog(@"query dict: %@", dict); } 

So you can do this:

 NSString * strNoURLScheme = [strMyURLWithScheme stringByReplacingOccurrencesOfString:[url scheme] withString:@""]; NSLog(@"URL without scheme: %@", strNoURLScheme); 

parseQueryString

 - (NSDictionary *)parseQueryString:(NSString *)query { NSMutableDictionary *dict = [[[NSMutableDictionary alloc] initWithCapacity:6] autorelease]; NSArray *pairs = [query componentsSeparatedByString:@"&"]; for (NSString *pair in pairs) { NSArray *elements = [pair componentsSeparatedByString:@"="]; NSString *key = [[elements objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSString *val = [[elements objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; [dict setObject:val forKey:key]; } return dict; } 
+11
source

My tendency is to collapse your own line to find this:

 NSRange dividerRange = [urlString rangeOfString:@"://"]; NSUInteger divide = NSMaxRange(dividerRange); NSString *scheme = [urlString substringToIndex:divide]; NSString *path = [urlString substringFromIndex:divide]; 

This does what you requested quite literally, dividing the URL in half according to your pattern. For more advanced processing, you will need to provide more detailed information.

+5
source

Remember, do not fight with wireframes, especially when it comes to NSURL. This SO answer has a good breakdown of his abilities. fooobar.com/questions/55782 / ...

The NSURL schema and path properties are exactly what you want (assuming the rest of your URL looks like a path) leaves you with this:

 NSString *schemeWithDelimiter = [NSString stringWithFormat:@"%@://",[myURL scheme]]; [[NSNotificationCenter defaultCenter] postNotificationName: schemeWithDelimiter object:[myURL path]; 

No string search required!

+1
source

Source: https://habr.com/ru/post/947269/


All Articles