等待json数据下载,然后快速加载页面

时间:2018-11-25 10:34:43

标签: ios json swift

将数据库中的json代码解析到iphone uilabel时遇到问题。该页面似乎加载速度更快,可以下载json数据。每次我运行它时,它总是留下一个空的UIlabel,但它确实在打印中显示。我该如何做,以便页面将等待json下载,然后可以继续显示其中包含json内容的页面。

页面,我正在使用放置在viewcontroller内的uiview

struct question:Decodable {
        let question:String
        let boxA:String
        let boxB:String
        let boxC:String
        let boxD:String
        let categories:String
    }
func getquestion(questions:String,url:String)->String{
        //return "which state that are bordering mexico?"
        let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
        request.httpMethod = "POST"
        let postString = "question=\(questions)"
        request.httpBody = postString.data(using: .utf8)
        var returns = ""
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
            if error != nil {
                print("error=\(String(describing: error))")
                return
            }
            // read the response from php
            do {
                let decoder = JSONDecoder()
                let product = try decoder.decode(question.self, from: data!)
                DispatchQueue.main.async{
                    returns = product.question
                }

            } catch let error as NSError {
                print(error)
            }
        }
        task.resume()
        return returns
    }

json页面

input

1 个答案:

答案 0 :(得分:1)

您需要完成

func getquestion(questions:String,url:String,completion:@escaping((_ str:String?)->())){
  //return "which state that are bordering mexico?"
  var request = URLRequest(url: URL(string: url)!)
  request.httpMethod = "POST"
  let postString = "question=\(questions)"
  request.httpBody = postString.data(using: .utf8)
  var returns = ""
  let task = URLSession.shared.dataTask(with: request as URLRequest) {
    data, response, error in
    if error != nil {
      print("error=\(String(describing: error))")
      completion(nil)
      return
    }
    // read the response from php
    do {
      let decoder = JSONDecoder()
     // let product = try decoder.decode(question.self, from: data!)
      DispatchQueue.main.async{
        completion(product.question)
      }

    } catch  {
      print(error)
      completion(nil)
    }
  }
  task.resume()

}

content = request.getquestion(questions: "212", url: "http://localhost/memory/question.php")
   { (str) in
  print(str)
}