Completion handlers in Swift 3.0

前端 未结 2 1261
终归单人心
终归单人心 2020-12-16 03:27

I am using the code below to sync data with my server. After completing the task, I would like to call:

self.refreshControl?.endRefreshing()
<
2条回答
  •  鱼传尺愫
    2020-12-16 04:04

    Swift 4:

    1. Create a completion block.

      func getDataFromJson(url: String, parameter: String, completion: @escaping (_ success: [String : AnyObject]) -> Void) {
      
          //@escaping...If a closure is passed as an argument to a function and it is invoked after the function returns, the closure is @escaping.
      
          var request = URLRequest(url: URL(string: url)!)
          request.httpMethod = "POST"
          let postString = parameter
      
          request.httpBody = postString.data(using: .utf8)
          let task = URLSession.shared.dataTask(with: request) { Data, response, error in
      
              guard let data = Data, error == nil else {  // check for fundamental networking error
      
                  print("error=\(error)")
                  return
              }
      
              if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {  // check for http errors
      
                  print("statusCode should be 200, but is \(httpStatus.statusCode)")
                  print(response!)
                  return
      
              }
      
              let responseString  = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String : AnyObject]
              completion(responseString)
      
      
      
          }
          task.resume()
      }
      
    2. Call method

      getDataFromJson(url: "http://example.com", parameter: "vehicle_type=Car", completion: { response in
              print(response)
      
          })
      

提交回复
热议问题