我正在尝试使用 window.location 将 url 从 JavaScript 传递到 Objective C。 我的 JavaScript 代码如下所示:
var str = "http://sampleurl:8080/abc";
window.location.href = "jscall:myapp:"+str;
在 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;
}
如果我只使用
NSString* str1 = (NSString *)[components objectAtIndex:2];
我只得到“http”。 如何限制字符串以将 ComponentsSeparatedByString 限制为 2?
最佳答案
您不能显式地仅拆分前两次出现的“:”,但是您可以轻松地使用另一种方法,因为您确切地知道字符串到“http”的位置。只需执行以下操作之一即可安全。
NSString *urlString = [requestString stringByReplacingOccurrencesOfString:@"jscall:myapp:" withString:@""];
或
NSUInteger prefixLength = @"jscall:myapp:".length;
NSString *urlString = [requestString substringFromIndex:prefixLength];
如果由于某种原因该字符串在请求中多次出现,第二个更可靠。
关于javascript - Objective C 组件通过字符串分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37963897/