OGeek|极客世界-中国程序员成长平台

标题: javascript - Objective-C 组件SeparatedByString [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 20:50
标题: javascript - Objective-C 组件SeparatedByString

我正在尝试使用 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?



Best Answer-推荐答案


您不能仅显式拆分前两次出现的 ':',但您可以轻松地使用另一种方法,因为您确切知道字符串在 '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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4