【问题标题】:iOS PickerView empty after read JsoniOS PickerView 读取 Json 后为空
【发布时间】:2016-11-19 18:43:42
【问题描述】:

我正在 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()
}

【问题讨论】:

  • self.picker.reloadAllComponents() 在您的方法 readJson 的调度主队列中添加这一行

标签: ios json swift3


【解决方案1】:

你需要做几件事:

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

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

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

(这是 Swift 3 的语法。)

编辑:

代码如下所示:

函数 readJson(){ 让 urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL) 让会话 = 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()

}

【讨论】:

  • 非常感谢邓肯。但是,该代码会引发错误:预期声明。
  • 我现在把它放在 viewDidLoad 的末尾,我仍然遇到同样的问题@Duncan C
  • 编辑您的问题以在最后显示您的新代码。
  • 完成,可以在@Duncan C 原帖中找到
  • 不,那是错误的。您需要将该代码放在会话任务的完成闭包中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-03
  • 2016-09-22
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
  • 1970-01-01
相关资源
最近更新 更多