2017-02-07 62 views
-3

我想获取json文件内容,但jsonData始终返回nil。这背后的原因是什么?Swfit Data无法获取值

enter image description here

OS:10.12.2的XCode:8.1雨燕3.0

+0

的我的代码是一个图片 –

+0

为什么不使用相关的API'后卫的URL让jsonURL = Bundle.main.url(forResource: “MainVCString”,withExtension: “JSON”)'?这避免了第二个“警卫”。并使用'do-catch'而不是'try?'来获取错误信息。 – vadian

+0

'URL(string:jsonPath)'应该是'URL(fileURLWithPath:jsonPath)' - 但是最好在@vadian建议的地方首先使用URL。 –

回答

0

你必须给路径的文件类型为JSON 作为

guard let jsonpath = bundle.main.path(forResource: "MainVCString", ofType: "json"), 
+0

不,它不能解决我的问题。jasonURL hava值。 –

0

这个怎么样?

if let fileURL = Bundle.main.url(forResource: "MainVCString", withExtension: "json"){ 
    if let data = try? Data(contentsOf: fileURL, options: Data.ReadingOptions.uncached){ 
     print("This works!") 
    }else{ 
     print("Something wrong with the path.") 
    } 
}