我创建了一个名为“ GetDataFromURL”的函数,该函数是获取数据表单URL并将其存储到本地Class Array对象中的主要任务。
使用URlSession.shared.dataTask函数,我将数据接收为DATA格式,然后通过使用jsonserialization.jsonObject方法获得json格式。响应是字典格式的,因此存储到临时类对象中,最后它将追加到全局类数组对象中。当Page称为“查看加载”方法时,将调用此函数。在函数内,它将显示所有数据,但是每次当我在块外显示时,当我得到nil数组对象时。
public class Modelclass : NSObject {
var id :Int!
var albumId : Int!
var title : String!
var url : String!
var thumbnailUrl : string!
}
这是类文件,下面是viewcontroller文件:
var temp:[ModelClass]?
override func viewDidLoad() {
super.viewDidLoad()
self.temp = [ModelClass]()
dispatchQueue.main.async{
self.GetDataFromURL()
}
print(self.temp,"Tesing print")
}
func GetDatafromURL() {
if let url = URL(string :
"https://jsonplaceholder.typicode.com/photos"){
URLSession.shared.dataTask(with: url){(data,response,error) in
if error != nil {
print(error)
return
}
do{
let jsonresponse = try jsonserialization.jsonObject(with:data! ,
options: .mutablecontainers)
for dictionary in jsonresponse as! [[String:AnyObject]]
{
var test = ModelClass()
test.title = dictionary["title"] as? String
test.albumId = dictionary["albumId"] as? Int
test.id = dictionary["id"] as? Int
test.thumbnailUrl = dictionary["thumbnailUrl"] as? String
test.url = dictionary["url"] as? String
self.temp?.append(test)
}
}
catch let jsonerror{
print(jsonerror)
}
}.resume()
}
}
它向我显示“ optional([])Tesing print”作为Output。在do块内打印该临时对象时,它将显示所有数据。
最佳答案
//添加此
var dispatchgroup = DispatchGroup()
//
var temp: [Modelclass] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.GetDatafromURL()
//Add this
dispatchgroup.notify(queue: .main){
print("temp data : \(self.temp.count)")
}
}
func GetDatafromURL() {
//add this
dispatchgroup.enter()
//
if let url = URL(string :
"https://jsonplaceholder.typicode.com/photos"){
URLSession.shared.dataTask(with: url){(data,response,error) in
if error != nil {
print(error)
return
}
do{
let jsonresponse = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
for dictionary in jsonresponse as! [[String:AnyObject]]
{
var test = Modelclass()
test.title = dictionary["title"] as? String
test.albumId = dictionary["albumId"] as? Int
test.id = dictionary["id"] as? Int
test.thumbnailUrl = dictionary["thumbnailUrl"] as? String
test.url = dictionary["url"] as? String
self.temp.append(test)
}
//add this
self.dispatchgroup.leave()
//
}
catch let jsonerror{
print(jsonerror)
}
}.resume()
}
}