指定API请求的参数

时间:2017-02-16 02:11:50

标签: ios swift macos object swift3

我对Swift很新,而且我不确定如何指定多个参数来向Yelp的API发出请求,因为我想知道如何在Swift3中完成这一操作以便我可以将响应变为JSON。 PS。目前正试图在Playground中得到回复,这是我到目前为止所得到的...谢谢

import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

let consumer_key = "YWRAq7EKtUk1U3wENMNKEvGgL"
let consumer_secret = "2e08byjGV1k0XvPcwUwBoIxMDT7RozjdmEdk03RqCvUMqtE7nH"
let access_token = "3681130275-Onust8RaEz7Yczw07sWz52vLsEnxRCnnFDXZ5qA"
let access_token_secret = "dwLn951PF4bCh96xd170NCGpgOb5iRkqwgoNvTignDEMq"

var request = URLRequest(url: URL(string: "https://api.yelp.com/v3/businesses/search")!)

request.setValue(access_token_secret, forHTTPHeaderField: "Authorization")

let session = URLSession.shared
session.dataTask(with: request) {data, response, err in
    do{
        let JSON = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary
        DispatchQueue.main.async {
        }
    }
    catch {
        print("json, error: \(error)")
    }
    }.resume()

3 个答案:

答案 0 :(得分:1)

您可以尝试这种方式 - :

let request = NSMutableURLRequest(URL: NSURL(string: "YourUrl")!)

    request.HTTPMethod = "POST"

   let params = ["key1":"val1","key2":"val2","key3":"val3"] as Dictionary<String, String>

    request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue(access_token_secret, forHTTPHeaderField: "Authorization")
    let task = URLSession.shared.dataTask(with: request, completionHandler: {data, response, error in
        print("Response: \(response)")})

    task.resume()

答案 1 :(得分:0)

这是用JSON发布的示例代码。 您的请求返回500错误结果。

工作样本:

let urlString = "https://httpbin.org/post"
var request = URLRequest(url: URL(string:urlString)!)

// set the method(HTTP-POST)
request.httpMethod = "POST"
// set the header(s)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

// set the request-body(JSON)
let params: [String: Any] = [
    "count": 1,
    "user": [
        "id": "10",
        "name": "jack"
    ]
]
do{
    request.httpBody = try JSONSerialization.data(withJSONObject: params, options: [])
}catch{
    print(error.localizedDescription)
}
// use NSURLSessionDataTask
let task = URLSession.shared.dataTask(with: request, completionHandler: {data, response, error in
    if (error == nil) {
        let result = String(data: data!, encoding: .utf8)!
        print(result)
    } else {
        print(error!)
    }
})
task.resume()

工作样本(yelp):

let consumer_key = "YWRAq7EKtUk1U3wENMNKEvGgL"
let consumer_secret = "2e08byjGV1k0XvPcwUwBoIxMDT7RozjdmEdk03RqCvUMqtE7nH"
let access_token = "3681130275-Onust8RaEz7Yczw07sWz52vLsEnxRCnnFDXZ5qA"
let access_token_secret = "dwLn951PF4bCh96xd170NCGpgOb5iRkqwgoNvTignDEMq"

let urlString = "https://api.yelp.com/v3/businesses/search"
var request = URLRequest(url: URL(string:urlString)!)

// set the method(HTTP-POST)
request.httpMethod = "POST"
// set the header(s)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(access_token, forHTTPHeaderField: "Authorization")

// set the request-body(JSON)
let params: [String: Any] = ["Authorization":access_token_secret]
do{
    request.httpBody = try JSONSerialization.data(withJSONObject: params, options: [])
}catch{
    print(error.localizedDescription)
}
// use NSURLSessionDataTask
let task = URLSession.shared.dataTask(with: request, completionHandler: {data, response, error in
    if (error == nil) {
        let result = String(data: data!, encoding: .utf8)!
        print("result:\(result)")
        // 500 Internal Server Error
    } else {
        print(error?.localizedDescription ?? "error")
    }
})
task.resume()

答案 2 :(得分:0)

以下是向具有多个参数的服务器发送请求的示例代码

let parameters = ["userId" : 1, "FullName" : "Robin Jackson"] // set all parameters in the [String : Any]



      RequestForPost("http://api.server.com/v1/name", parameters)

func RequestForPost(url:String, postData:[String : Any]) -> Void {

        let request = createRequest(parameter: postData, strURL: url as NSString) // This is we create request
        let session = URLSession.shared
        session.configuration.timeoutIntervalForRequest = 30.0 //Time out for request
        session.configuration.timeoutIntervalForResource = 60.0

        let task = session.dataTask(with: request as URLRequest) { data, response, error in
            if error != nil {
                print("Error Occurred:\(error?.localizedDescription)")
                return
            }
            do {
                let httpResponse = response as? HTTPURLResponse
                if httpResponse?.statusCode == 200 {
                    if let responseDictionary = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any] {
                        print(responseDictionary)
                    }
                }
                else if httpResponse?.statusCode == 400 {
                    let responseString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
                    print(responseString ?? "")
                }
                else {
                    let responseString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
                    print("Error occurred:\(error?.localizedDescription)")
                }
            }
            catch {
                let responseString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
                print("Error occurred:\(error.localizedDescription)")
            }
        }
        task.resume()
    }

        func createRequest(parameter: [String : Any],strURL:NSString) -> NSURLRequest {
                let url = URL(string: strURL as String)!
                let request = NSMutableURLRequest(url: url) //Set URL Of server
    request.setValue(secretToken, forHTTPHeaderField: "x-auth-token") //Set header field value like "Content-Type"
                request.httpMethod = "POST" // HTTMMethods "POST", "GET", "PUT" & "DELETE"
                var requestBody = ""
                for key in parameter.keys{
                    if requestBody == "" {
                        requestBody = "\(key)=\(parameter[key]!)"
                    }
                    else {
                        requestBody = "\(requestBody)&\(key)=\(parameter[key]!)"
                    }
                }
                request.httpBody = requestBody.data(using: String.Encoding.utf8) // Set Parameters to httpbody
                return request
            }