处理背靠背HTTP帖子SWIFT 4.0

时间:2017-10-20 09:26:02

标签: ios swift api post swift4

我目前正在尝试从服务器获取一些数据。为此,我必须创建一个JSON(req1)对象并将其作为请求发送到第一个API。然后,API返回给我一个JSON(res1)。从那个JSON(res1),我必须提取一些数据(非常冗长,让我们称之为Data1)并创建另一个JSON对象(req2)并使用它作为请求命中另一个API并等待响应(res2) )。

现在,它是一个背靠背功能。当我调用第一个API时,需要很长时间才能响应,到那时,我的第二个API被调用。因此,我从服务器收到错误。我该怎么过来呢?

ALGO:

  1. 调用API_A()
  2. 收到JSON_A
  3. 提取JSON_A 4.Call API_B(JASON_A.someparts)
  4. 收到JSON_B
  5. 提取JSON_B
  6. 下面是代码:

    
    
    let json1 = JSON()
    let json2 = JSON() //my final result
    
    override func viewDidLoad() {
            super.viewDidLoad()
    	    firstApiHit { () -> () in
                secondApiHit(jsonV: json1)
            }
        }
    
    func firstApiHit(handleComplete:(()->())){
    	let url1 = URL(string : firstApiURL) 
    	let json: [String: String] = ["Data1:Data1Rest"]
    	let jsonData = try? JSONSerialization.data(withJSONObject: json)
    	json1 = httpPost(jsonData: jsonData!, url: url1!)  //hit to the first API!
    	handleComplete()
    }
    
    func secondApiHit(jsonV : JSON){
    	let url1 = URL(string : secondApiURL)
    	var value = String()
    	extractedValue = String(describing:jsonV["DataX"])
    	var json = [String: String]()
    	json = ["Data1":extractedValue]
    	let jsonData = try? JSONSerialization.data(withJSONObject: json)
        let json2 = httpPost(jsonData: jsonData!, url: url2!) // my final result!
    		//Need the json2 as the final Result!!
    }
        
    func httpPost(jsonData: Data, url: URL) -> JSON {
    	if !jsonData.isEmpty {
    		var request = URLRequest(url: url)
    		request.httpMethod = "POST"
    		request.httpBody = jsonData
    		request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    		URLSession.shared.getAllTasks { (openTasks: [URLSessionTask]) in
    									   print("open tasks: \(openTasks)")
    									  }
    		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=\(String(describing: 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 = \(String(describing: response))")
    			}
    																  
    			let jsonX = JSON(data: data) //extracting the data! 
    		}	
        	task.resume()
    	}
        return jsonM
    }
    
    
    

1 个答案:

答案 0 :(得分:0)

httpPost(...)URLSession.shared.dataTask(...)完成之前返回,因为后者是异步运行的。

firstApiHit(...)中,您不应该致电handleComplete(),而应将其传递给httpPost(...)。您还需要将JSON作为参数传递。

override func viewDidLoad() {
    super.viewDidLoad()
    firstApiHit { json in
        secondApiHit(jsonV: json)
    }
}

func firstApiHit(handleComplete: JSON -> Void){
    ...
    json1 = httpPost(jsonData: jsonData!, url: url1!, handleComplete)
}

func httpPost(jsonData: Data, url: URL, responseHandler: (JSON) -> Void) {
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        ...                                   
        let jsonX = JSON(data: data)
        responseHandler(jsonX)
    }   
}

肯定需要学习如何使用闭包,更具体地说,需要学习响应处理程序模式。否则你会一次又一次陷入痛苦的世界。