2017-02-16 12 views
0

私はSwiftにとって非常に新しく、YelpのAPIへのリクエストを行うために複数のパラメータを指定する方法がわからないので、Swift3でどのようにできるのだろうかと思っていたレスポンスをJSONに変換します。 PS。現在、私がこれまで持っているものです...おかげAPIリクエストのパラメータを指定する

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() 
+0

でサーバーにリクエストを送信するためのサンプルコードですhttps://github.com/codepath/ios_yelp_swift/tree/master/Yelp – Vinodh

+0

@Vinodhあなたが提供したソースはYelpを使用していますV2。 OPはYelp V3を使用しています。 – htjohn

答えて

1

は、あなたがこのway-を試すことができ、ここで、遊び場での応答を取得しよう:

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() 
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() 
0

が、これはYelpので提供してみてください、複数のPARAMATERS

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 
      } 
関連する問題