阅读Json后iOS PickerView为空

时间:2016-11-19 18:43:42

标签: ios json swift3

我在iOS上制作应用程序,一切都进展顺利,但是我无法修复一个错误。当用户第一次启动应用程序时,应用程序从我的服务器请求json。读取json时,我会在选择器视图中显示结果。问题是,在用户触摸屏幕之前,pickerview始终显示为空。我尝试了很多东西,但没有任何作用。理论上它是空的,因为json还没有读过,但事实并非如此,因为在控制台中我可以看到json已经准备就绪。

以下是相关的代码:

override func viewDidLoad() {

    super.viewDidLoad()

    warning.isHidden = true
    self.codeInput.delegate = self;

    DispatchQueue.main.async {
        self.readJson()
        self.picker.reloadAllComponents()
    }
 }

我阅读json的部分

  func readJson(){
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL)
    let session = URLSession.shared
    let task = session.dataTask(with: urlRequest as URLRequest, completionHandler: {
        (data, response, error) -> Void in

        let httpResponse = response as! HTTPURLResponse
        let statusCode = httpResponse.statusCode


        if (statusCode == 200) {
            print("Everyone is fine, file downloaded successfully.")
            do{

                let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]

                if let events = json["events"] as? [[String: AnyObject]] {

                    for event in events {

                        //here I read the json and I save the data in my custom array
                        }
                        self.picker.reloadAllComponents()
                    }
                    print(self.eventsArray)
                }

            }catch {
                print("Error with Json: \(error)")
            }
        }
        else{
            print(statusCode)
        }
    })
    picker.reloadAllComponents()
    task.resume()
}

1 个答案:

答案 0 :(得分:1)

你需要做几件事:

您需要移动调用以将选择器视图重新加载到数据任务的完成处理程序内部。一旦加载了数据,就会调用该闭包。

但是,URLSession任务的完成方法在后台线程上执行。因此,您需要在对主线程的GCD调用中包装您的调用。将此代码添加为完成闭包中的最后一行,就在右大括号之前:

DispatchQueue.main.async{
    picker.reloadAllComponents()
}     

(那是Swift 3的语法。)

编辑:

代码如下所示:

func readJson(){     let urlRequest:NSMutableURLRequest = NSMutableURLRequest(url:requestURL)     let session = URLSession.shared     let task = session.dataTask(with:urlRequest as URLRequest,completionHandler:{         (数据,响应,错误) - >无效

    let httpResponse = response as! HTTPURLResponse
    let statusCode = httpResponse.statusCode


    if (statusCode == 200) {
        print("Everyone is fine, file downloaded successfully.")
        do{

            let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]

            if let events = json["events"] as? [[String: AnyObject]] {

                for event in events {

                    //here I read the json and I save the data in my custom array
                    }
                    //Delete this call to reloadAllComponents()
                    //self.picker.reloadAllComponents()
                }
                print(self.eventsArray)
            }
            //------------------------------------
            //This is where the new code goes
            DispatchQueue.main.async{
                picker.reloadAllComponents()
            }     
            //------------------------------------
        }catch {
            print("Error with Json: \(error)")
        }
    }
    else{
        print(statusCode)
    }
})
//Delete this call to reloadAllComponents()
//picker.reloadAllComponents()
task.resume()

}