我所看到或阅读的有关Swift 3 JSON解析的所有教程都包括将JSON解析代码放在viewDidLoad()
func / method中,并且它运行良好。我想将JSON解析代码放在它自己的函数中,并从viewDidLoad()
调用它。检查以下示例:
class ViewController: UIViewController {
var ArrayImages = [String]();
override func viewDidLoad() {
super.viewDidLoad()
var json = ParseJson();
print("My Array = \(ArrayImages)");
}
// NEW FUNCTION
func ParseJson() {
let url = URL(string: "http://etasawoq.com/go_categories.php")!
URLSession.shared.dataTask(with: url) { (data, response, error) in
if (error != nil){
print("Error Found Creating URLSession : \(error)")
} else {
if let ParsedJson = data {
do {
let json = try JSONSerialization.jsonObject(with: ParsedJson, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
for x in json {
let row = x as! NSDictionary;
let imageUrl = row["image_url"] as! String
self.ArrayImages.append(imageUrl);
}
} catch {
print("Json Processing failed \(error)");
}
}
}
}.resume() // start session
}
}
不幸的是," ArrayImages"调用ParseJson
函数时未填充。打印输出是"我的数组= []"。这是为什么?如何在将JSON解析代码保存在单独的函数中的同时解决此问题?
答案 0 :(得分:0)
您的回复是通过阻止所以您需要在不在外面的块旁边打印数组,如下所示。
do {
let json = try JSONSerialization.jsonObject(with: ParsedJson, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
for x in json {
let row = x as! NSDictionary;
let imageUrl = row["image_url"] as! String
self.ArrayImages.append(imageUrl);
}
print("My Array = \(ArrayImages)");
}