gpt4 book ai didi

javascript - Objective C 组件SeparatedByString

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:30:41 27 4
gpt4 key购买 nike

我正在尝试使用 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 组件SeparatedByString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37963897/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com