3
我試圖在使用built-in REST API創建的分析數據庫上發出GET請求。當用戶將文本輸入到UISearchBar中時,將調用API調用,最終目標是在UITableView中顯示返回的數據。下面的代碼僅捕獲我嘗試創建一個有效的HTTP請求,其中我試圖查看「Query1」是否與搜索字符串匹配(「Query1」是我的Parse數據庫中的一個參數,基本上用作關聯的搜索字詞)。使用分析查詢在Swift中調用REST API
//Mark - UISearchBarDelegate
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
makeRequest(searchBar.text)
}
func makeRequest (searchString : String) {
//REST API call to the sampleObjectData class
var request = NSMutableURLRequest(URL: NSURL(string: "https://api.parse.com/1/classes/sampleObjectData")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
//THIS IS MY TROUBLE AREA
var params = urllib.urlencode({"where";:json.dumps({
"Query1": "\(searchString)"
})})
var error: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &error)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//The kAppId & kRestAPIKey calls are referencing contstants at the top of the file
request.addValue("X-Parse-Application-Id", forHTTPHeaderField: kAppId)
request.addValue("X-Parse-REST-API-Key", forHTTPHeaderField: kRestAPIKey)
var task = session.dataTaskWithRequest(request, completionHandler: { (data, response, err) -> Void in
var stringData = NSString(data: data, encoding: NSUTF8StringEncoding)
println(stringData)
})
task.resume()
}
結果是不會構建的代碼,因爲我無法弄清楚如何使用Swift將參數應用於Parse REST API。任何幫助,將不勝感激。
在iOS 9中,不建議使用'stringByAddingPercentEscapesUsingEncoding'。這相反:'stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())' – Joey 2015-09-28 06:45:13