Solución:
En una prueba unitaria probablemente quieras usar [NSBundle bundleForClass:[self class]]
, y no [NSBundle mainBundle]
. Eso es porque la prueba unitaria no es una aplicación independiente. Con mainBundle
obtienes algo como /Applications/Xcode.app/Contents/Developer/Tools
, pero usando bundleForClass
le ofrece el paquete donde se encuentra su clase de prueba unitaria.
guard let pathString = Bundle(for: type(of: self)).path(forResource: "UnitTestData", ofType: "json") else {
fatalError("UnitTestData.json not found")
}
En Swift
Swift 5 y superior
guard let pathString = Bundle(for: type(of: self)).path(forResource: "UnitTestData", ofType: "json") else {
fatalError("UnitTestData.json not found")
}
guard let jsonString = try? String(contentsOfFile: pathString, encoding: .utf8) else {
fatalError("Unable to convert UnitTestData.json to String")
}
print("The JSON string is: (jsonString)")
guard let jsonData = jsonString.data(using: .utf8) else {
fatalError("Unable to convert UnitTestData.json to Data")
}
guard let jsonDictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String:Any] else {
fatalError("Unable to convert UnitTestData.json to JSON dictionary")
}
print("The JSON dictionary is: (jsonDictionary)")
Swift 3 y 4
guard let pathString = Bundle(for: type(of: self)).path(forResource: "UnitTestData", ofType: "json") else {
fatalError("UnitTestData.json not found")
}
guard let jsonString = try? NSString(contentsOfFile: pathString, encoding: String.Encoding.utf8.rawValue) else {
fatalError("Unable to convert UnitTestData.json to String")
}
print("The JSON string is: (jsonString)")
guard let jsonData = jsonString.data(using: String.Encoding.utf8.rawValue) else {
fatalError("Unable to convert UnitTestData.json to NSData")
}
guard let jsonDictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String:AnyObject] else {
fatalError("Unable to convert UnitTestData.json to JSON dictionary")
}
print("The JSON dictionary is: (jsonDictionary)")
Swift 2.2
guard let pathString = NSBundle(forClass: self.dynamicType).pathForResource("UnitTestData", ofType: "json") else {
fatalError("UnitTestData.json not found")
}
guard let jsonString = try? NSString(contentsOfFile: pathString, encoding: NSUTF8StringEncoding) else {
fatalError("Unable to convert UnitTestData.json to String")
}
print("The JSON string is: (jsonString)")
guard let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding) else {
fatalError("Unable to convert UnitTestData.json to NSData")
}
guard let jsonDictionary = try? NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? [String:AnyObject] else {
fatalError("Unable to convert UnitTestData.json to JSON dictionary")
}
print("The JSON dictionary is: (jsonDictionary)")
* Esto incorpora la respuesta de Tom Harrington que está en el Objetivo C
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)