gpt4 book ai didi

cocoa - Swift 示例和 RESTful API 的 Put 请求

转载 作者:搜寻专家 更新时间:2023-10-30 22:31:36 26 4
gpt4 key购买 nike

我正在尝试通过为 Phillips Hue light API 创建一个 OSX 应用程序来学习 Swift。但是,我在这里觉得很傻,我什至无法让一个简单的例子起作用。我在 X Code 6.1 中使用这个库: https://github.com/hallas/agent

这是我使用的代码:

import Foundation



let done = { (response: NSHTTPURLResponse!, data: Agent.Data!, error: NSError!) -> Void in
// react to the result of your request
};
Agent.put("/api/[username]/lights/2/state", headers: [ "Header": "Value" ],
data: [ "hue": 35000 ], done: done)

不用说它什么也没做。我做错了什么?

最佳答案

这是一个 PUT 操作的示例,使用一个简单的类来包装 HTTP 功能:

    let url = NSURL(string:"http://example.com")
let text = "Text to PUT"
var myData: NSData? = text.dataUsingEncoding(NSUTF8StringEncoding)
var headers = Dictionary<String, String>()

Http().put(url!, headers: headers, data:myData!) { (result) in
if result.success {
if let jsonObject: AnyObject = result.jsonObject {
println(jsonObject)
}
}
}

class Http {

func put(url: NSURL, headers: Dictionary<String, String>, data: NSData, completionHandler: ((result: HttpResult) -> Void)!) {
action("PUT", url: url, headers: headers, data: data ) { (result) in
completionHandler(result: result)
}
}

func action(verb: String, url: NSURL, headers: Dictionary<String, String>, data: NSData, completionHandler: ((result: HttpResult) -> Void)!) {
let httpRequest = NSMutableURLRequest(URL: url)
httpRequest.HTTPMethod = verb

for (headerKey, headerValue) in headers {
httpRequest.setValue(headerValue, forHTTPHeaderField: headerKey)
}
let task = NSURLSession.sharedSession().uploadTaskWithRequest(httpRequest, fromData: data) { (data, response, error) in
completionHandler(result: HttpResult(data: data, request: httpRequest, response: response, error: error))
}
task.resume()
}
}

class HttpResult {

var request: NSURLRequest
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
var statusCode: Int = 0
var success: Bool = false
var headers : Dictionary<String, String> {
get {
if let responseValue = response {
return responseValue.allHeaderFields as Dictionary<String,String>
}
else {
return Dictionary<String, String>()
}
}
}

init(data: NSData?, request: NSURLRequest, response: NSURLResponse?, error : NSError?) {
self.data = data
self.request = request
self.response = response as NSHTTPURLResponse?
self.error = error
self.success = false

if error != nil {
println("Http.\(request.HTTPMethod!): \(request.URL)")
println("Error: \(error!.localizedDescription)")
}
else {
if let responseValue = self.response {
statusCode = responseValue.statusCode
if statusCode >= 200 && statusCode < 300 {
success = true
}
else {
println("Http.\(request.HTTPMethod!) \(request.URL)")
println("Status: \(statusCode)")
if let jsonError: AnyObject = jsonObject {
var err: NSError?
var errData = NSJSONSerialization.dataWithJSONObject(jsonError, options:NSJSONWritingOptions.PrettyPrinted, error: &err)
var errMessage = NSString(data: errData!, encoding: NSUTF8StringEncoding)
println("Error: \(errMessage)")
}
}
}
}
}

var jsonObject: AnyObject? {
var resultJsonObject: AnyObject?
var jsonError: NSError?
if let contentType = headers["Content-Type"] {
if contentType.contains("application/json") {
resultJsonObject = NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments, error: &jsonError) as AnyObject?
}
}
return resultJsonObject
}
}

关于cocoa - Swift 示例和 RESTful API 的 Put 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26617607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com