Ios 如何在swift框架中获取json文件路径并从中获取数据?
我不熟悉使用JSON解析数据,在Swift框架中使用它,并在计算后将其发送到应用程序进行显示 我尝试了下面的代码来打开一个Json文件并读取它,但由于返回到路径中的值为零,我总是以“无效文件路径”结束Ios 如何在swift框架中获取json文件路径并从中获取数据?,ios,json,swift,frameworks,nsbundle,Ios,Json,Swift,Frameworks,Nsbundle,我不熟悉使用JSON解析数据,在Swift框架中使用它,并在计算后将其发送到应用程序进行显示 我尝试了下面的代码来打开一个Json文件并读取它,但由于返回到路径中的值为零,我总是以“无效文件路径”结束 if let path = NSBundle.mainBundle().pathForResource("furnitures", ofType: "json") { print(path) do { let jsonData = try NSData(conte
if let path = NSBundle.mainBundle().pathForResource("furnitures", ofType: "json") {
print(path)
do {
let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
do {
let jsonResultDict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if let furnTyp : [NSDictionary] = jsonResultDict["furnTypes"] as? [NSDictionary] {
for furType: NSDictionary in furnTyp {
for (name,value) in furType {
if name as! String == "sofa" {
print(value)
}
}
}
}
} catch {
"exception at NSJSONSerialization"
}
} catch {
print("exception at NSData")
}
}
else {
print("Invalid file Path")
}
此外,我还尝试了以下代码来获取路径,并将其传递给NSData以获取文件的内容,结果在NSData处出现异常
let file = "furnitures.json"
var jsonFilePath: String! = nil
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
//path will be stored here
jsonFilePath = dir.stringByAppendingPathComponent(file);
print(jsonFilePath) // printing the file path
}
因此,请帮助我解决这个问题
提前感谢感谢Anupam Mishra编辑我的文章