swift 从 json 对象中放入 API

swift PUT API from json object

我正在尝试构建 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';

Swift 构建 json 对象的代码

/// 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!)

通过对您的 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 **********/
}