尝试从ClassA解析Json文件并在ClassB中获取结果。
ClassB在ViewDidLoad()上调用getResultfromA()方法;它从ClassA获取解析结果,然后显示在与ClassB
关联的标签视图中问题部分: - 结果在ClassB中打印为nil,但在一秒左右后,解析后的结果将打印在ClassA中,
结论: - 据我所知,我在异步任务中做了一些愚蠢的事情,它应该让ClassB中的任务等到从ClassA收到数据,这就是所期望的最终结果应该是
ClassA () {
func getJsonBookDetails(isbnString:String) -> Dictionary<String, String>{
var gBooks = Dictionary<String, String>()
let scriptUrl = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbnString
let myurl = URL(string:scriptUrl)
let request = NSMutableURLRequest(url: myurl!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: myurl! ) { (data, response, error) in
if error != nil{
print("THIS ERROR",error!)
return
} else{
if let mydata = data{
do{
let myJson = try (JSONSerialization.jsonObject(with: mydata, options: JSONSerialization.ReadingOptions.mutableContainers)) as AnyObject
if let dictonary = myJson["items"] as? NSArray {
--/* parsed results stored in dictionary gBooks*/---
}
/* trying to send dictionary gBooks to ClassB */
var myVar = ClassB()
OperationQueue.addOperation()
/* */
} catch{
print("Error found")
}
}
}
}
task.resume()
return gBooks
}
}
这适用于ClassB,其结果是显示的
ClassB {
var userGbook = [String:String]()
override func viewDidLoad() {
super.viewDidLoad()
getResultfromB()
}
func getResultfromA(){
/* call func getJsonBookDetails() from classA and store in
userGbook /*
/* display the result stored in associated labels using the keys form the dictionary */
}
}