javascript - 如何将 NSArray 传递给 JavaScript 文件并在 JavaScript 中打印该数组?

标签 javascript ios objective-c cordova nsarray

我正在寻找从 viewcontroller.m 文件发送一个 NSArray 到 data.js 文件 但它不会在 JavaScript 中打印任何内容。以下是我的代码。

在我的viewdidload方法中

   - (void)webViewDidFinishLoad:(UIWebView*)theWebView
{
    // Black base color for background matches the native apps
    CDV=[[CDVViewController alloc]init];
    news=[[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"latest news" ofType:@"plist"]];
    NSArray *newsItems=[[NSArray alloc]init];
    newsItems=[news valueForKey:@"News"];
    NSData *jsonArray = [self arrayToJSON:newsItems];
    NSString *jsonString = [[NSString alloc] initWithData:jsonArray
                                                 encoding:NSUTF8StringEncoding];
    NSString *jsCall = [NSString stringWithFormat:@"yourJsFunction([%@])", jsonString];
    [theWebView stringByEvaluatingJavaScriptFromString:jsCall];
   NSLog(@"%@",jsonString);
   // theWebView.backgroundColor = [UIColor blackColor];

    return [super webViewDidFinishLoad:theWebView];
}


   - (NSData *) arrayToJSON:(NSArray *) inputArray
{
    NSError *error = nil;
    id result = [NSJSONSerialization dataWithJSONObject:inputArray
                                                options:kNilOptions error:&error];
    if (error != nil) return nil;
    return result;
}

在我的 one.js 文件中有这段代码:

function yourJsFunction(arr){
    for(var i=0;i<arr.length;i++){
        document.write(arr[i]);
    }
    return arr;
}

输出是:

ഡാറ്റാസെന്റർ:സത്യവാങ്മൂലംസമർപ്പിക്കാൻഅനുമതി‌,കാശ്മീർയുയു.

但我想要他们每个人分开而不是把“,”

当前输出:

enter image description here

新形象 enter image description here

最佳答案

js文件有一些变化
1.使用 toString() 将 arr 转换为正确的字符串 2.拆分新字符串

var b=arr.toString().split(',');

现在打印 document.write(b[1]);它的工作!!!!!

在 .m 文件中就像“@Divaka”的选项

尝试在此处更改选项 NSJSONSerialization dataWithJSONObject:从 kNilOptions 到 NSJSONWritingPrettyPrinted

关于javascript - 如何将 NSArray 传递给 JavaScript 文件并在 JavaScript 中打印该数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19488284/

相关文章:

javascript - Yii2。 $(document).ready 故障排除

javascript - 如何在 React 中的 props 中发送两个参数函数?

ios - iOS 应用程序 "reregister"可以在不重新安装的情况下处理 URL 方案吗?

c# - UIScreen.MainScreen.Bounds.Height 和 UIScreen.MainScreen.Bounds.Width 都是 0

ios - 如何在标签中显示文本字段验证错误消息

objective-c - 在 UICollectionView 上使用 AVPlayer 和 AVPlayerLayer 显示多个视频

ios - 从 Swift 类在 Objective-C 类的类方法 (+) 中传递参数

javascript - DroidScript - TCP 随时接收

javascript - 使用jQuery双击后追加textarea

ios - NSJSONSerialization 错误 : Why am I not able to catch the error in try catch block? swift 3.0