javascript - Objective C 组件通过字符串分隔

标签 javascript ios objective-c string

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

相关文章:

ios - 快速开发 : How can I check if my local development api server is running?

ios - 如何将手势和动画结合在一起

ios - 如何从URL确定文件的文件扩展名(Objective-C)

javascript - 更简单或更好的方法来检查 jqxgrid 是否没有要显示的数据(为空)?

javascript - 在 Typescript 中使用多个字符串数组

javascript - 收到回发后刷新网页

IOS 将 UIProgressView 添加到 AVFoundation AVCaptureMovieFileOutput

javascript - 为什么 Chrome 显示一个值在它被删除之前从数组中删除?

ios - 如何在 Swift 中以十六进制设置(初始化)unichar/UInt16 的值

ios - 读取 iOS 上其他应用的 badge 值