SwiftCake SwiftCake - 5 months ago 38
Objective-C Question

Objective C componentsSeparatedByString

I'm trying to pass a url from JavaScript to Objective C using window.location.
My JavaScript code looks like this:

var str = "http://sampleurl:8080/abc";
window.location.href = "jscall:myapp:"+str;


In Objective C:

NSString *requestString = [[request URL] absoluteString];
NSArray *components = [requestString componentsSeparatedByString:@":"];

if ([components count] > 1 &&
[(NSString *)[components objectAtIndex:0] isEqualToString:@"jscall"]) {
if([(NSString *)[components objectAtIndex:1] isEqualToString:@"myapp"])
{
NSLog([components objectAtIndex:2]); //this returns just "http"

NSString* str1 = (NSString *)[components objectAtIndex:2];
NSString* str2 = (NSString *)[components objectAtIndex:3];
NSString* str3 = (NSString *)[components objectAtIndex:4];
str2 = [str2 stringByAppendingString:@":"];
str2 = [str2 stringByAppendingString:str3];
str1 = [str1 stringByAppendingString:@":"];
self.jsLbl.text = [str1 stringByAppendingString:str2];
//The output of this is "http://sampleurl:8080/abc"
}
return NO;
}


If I use just

NSString* str1 = (NSString *)[components objectAtIndex:2];


I am getting only "http".
How can I restrict the string to limit componentsSeparatedByString by 2?

Answer

You can't explicitly split only the first two occurrences of ':', but what you could easily do is just use another method as you know exactly what the string is up to the point of the 'http'. It would be safe to just do one of the following.

NSString *urlString = [requestString stringByReplacingOccurrencesOfString:@"jscall:myapp:" withString:@""];

or

NSUInteger prefixLength = @"jscall:myapp:".length;
NSString *urlString = [requestString substringFromIndex:prefixLength];

The second one is more reliable incase for some reason there were multiple occurrences of that string in the request.