【发布时间】:2017-05-04 21:49:30
【问题描述】:
我正在尝试创建 json 对象的 api 调用。但是数据没有被传递我相信这是传递时数据的格式服务只有我在下面发布的php示例
API 文档:http://middleware.idxbroker.com/docs/api/methods/index.html#api-Leads-putLead
php 调用
// PUT lead in to IDX Broker
$url = 'https://api.idxbroker.com/leads/lead';
$data = array(
'firstName'=>$firstname,
'lastName'=>$lastname,
'email'=>$email
);
$data = http_build_query($data); // encode and & delineate
$method = 'PUT';
构建 json 对象的 Swift 代码
/// Create lead from text fields
let jsonObject: [String: String] = [
"firstName": (firstName.text! as String),
"lastNmae": lastName.text!,
"email": Email.text!,
"phoneNumber": phoneNumber.text!,
"city": (city.text as AnyObject) as! String,
"recieveUpdates": (switchIsChanged(recieveUpdates: recieveUpdates) as AnyObject) as! String
]
API 调用
class func putLead(lead: AnyObject){
let urlString = "https://api.idxbroker.com/leads/lead"
let url = NSURL(string: urlString)
print(lead)
var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
/******************** Add Headers required for API CALL *************************************/
downloadTask.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
downloadTask.setValue(APICalls.getAccessKey(), forHTTPHeaderField: "accesskey")
downloadTask.setValue("json", forHTTPHeaderField: "outputtype")
downloadTask.httpMethod = "PUT"
downloadTask.httpBody = (lead as? Data)
/******************** End Headers required for API CALL *************************************/
URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in
/// Status Returned from API CALL
if let httpResponse = response as? HTTPURLResponse {
print("statusCode: \(httpResponse.statusCode)")
}
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonData ?? "No Return")
}).resume()
/******** End URL Session **********/
}
工作版本
let newLead = "firstName=\(firstName.text!)&lastName=\(lastName.text!)&email=\(Email.text!)&phoneNumber=\(phoneNumber.text!)&city=\(String(describing: city.text))&recieveUpdates=\((switchIsChanged(recieveUpdates: recieveUpdates) as AnyObject) as! String)"
let newData = newLead.data(using: String.Encoding.utf8)
/// API Call with passing json String
APICalls.putLead(lead: newData!)
【问题讨论】:
-
如何用
jsonObject调用putLead()??你做let json = try? JSONSerialization.data(withJSONObject: jsonObject, options: []),self.putLead(json)`吗? -
不,我只是传递 Json 对象
-
应该如何将
[String:String]的演员阵容转换为Data?使用JSONSerialization。 -
我试过 do{ let data = try JSONSerialization.data(withJSONObject: jsonObject, options: []) /// API 调用,传递 json 字符串 APICalls.putLead(lead: data as AnyObject) } catch { } 但我收到错误未提供必填字段
-
这可能只是针对您的实际目的的另一个试验。你最好留在你的old Q,这将为读者提供更多信息。你知道你可以编辑你的问题。