【问题标题】:swift PUT API from json object来自 json 对象的 swift PUT API
【发布时间】: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,这将为读者提供更多信息。你知道你可以编辑你的问题。

标签: php json swift api put


【解决方案1】:

我能够通过对您的 putLead() 函数进行以下更改来使其工作:

class func putLead(lead: [String:String]){
    let urlString = "https://api.idxbroker.com/leads/lead"
    let url = NSURL(string: urlString)

    var httpBodyString = ""
    for (key,value) in lead{
        let currentKey = key.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        let currentValue = value.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        httpBodyString += "\(currentKey!)=\(currentValue!)&"
    }

    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(<API_KEY_HERE>, forHTTPHeaderField: "accesskey")
    downloadTask.httpMethod = "PUT"
    downloadTask.httpBody = httpBodyString.data(using: String.Encoding.utf8)
    /******************** 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 **********/
}

【讨论】:

    猜你喜欢
    • 2015-11-09
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 2016-02-01
    • 2017-02-10
    • 2014-03-12
    • 1970-01-01
    • 2019-03-11
    相关资源
    最近更新 更多