Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 为API请求指定参数_Ios_Swift_Macos_Object_Swift3 - Fatal编程技术网

Ios 为API请求指定参数

Ios 为API请求指定参数,ios,swift,macos,object,swift3,Ios,Swift,Macos,Object,Swift3,我对Swift非常陌生,我不确定如何指定多个参数来请求Yelp的API,因为我想知道如何在Swift3中完成这一点,以便将响应转换为JSON。另外,目前我正试图在操场上得到回应,以下是我目前所得到的。。。谢谢 import UIKit import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true let consumer_key = "YWRAq7EKtUk1U3wENMNKEvGgL" let

我对Swift非常陌生,我不确定如何指定多个参数来请求Yelp的API,因为我想知道如何在Swift3中完成这一点,以便将响应转换为JSON。另外,目前我正试图在操场上得到回应,以下是我目前所得到的。。。谢谢

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()
你可以这样试试-:

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()
let request=NSMutableURLRequest(URL:NSURL(字符串:“YourUrl”)!)
request.HTTPMethod=“POST”
让params=[“key1”:“val1”,“key2”:“val2”,“key3”:“val3”]作为字典
request.HTTPBody=试试看!NSJSONSerialization.dataWithJSONObject(参数,选项:[])
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
request.setValue(访问\u令牌\u秘密,forHTTPHeaderField:“授权”)
让task=URLSession.shared.dataTask(with:request,completionHandler:{data,response,error in
打印(“响应:\(响应)”)}
task.resume()

这是在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 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
            }

试试Yelp@Vinodh提供的这个,您提供的源代码使用的是YelpV2。OP正在使用Yelpv3。
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
            }