2014-10-28 13 views
5

Sto cercando di imparare Swift creando un'app OSX per l'API di luce Phillips Hue. Tuttavia, e mi sento stupido qui, non riesco nemmeno a far funzionare un semplice esempio. Sto usando questa libreria in X Codice 6.1: https://github.com/hallas/agentEsempio di richiesta Swift e Put per un'API RESTful

Ecco il codice che sto utilizzando:

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) 

Inutile dire che la sua non fare nulla. Che cosa sto facendo di sbagliato?

+0

Come fai a sapere che si tratta di non sta facendo niente? – GoZoner

+0

Sto usando l'interfaccia web di Phillips Hue e faccio un GET per lo stato di tutte le lampadine. I numeri non sono cambiati. –

+2

La chiusura 'done' è vuota; forse 'Agent.put()' sta segnalando un errore? Usa 'se errore! = Null {/ * stampa qualcosa; pausa del debugger; ecc * /} ' – GoZoner

risposta

6

Questo è un esempio di un'operazione PUT, utilizzando una semplice classe per avvolgere la funzionalità 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 
}  
} 
+0

Ack, scusa pensavo che volessi fare un PUT dritto, solo visto la tua domanda sembra specifica dell'SDK. – Lee

+0

Non posso usare il tuo codice per il mio problema? –

+0

Sì, funzionerà perfettamente per eseguire un'API REST PUT, ma non è specifico per Phillips Hue. – Lee

1

Prima di esaminare il codice. Si prega di assicurarsi di aver seguito la guida iniziare a ricevere dalla pagina web tonalità sviluppatore http://www.developers.meethue.com/documentation/getting-started

Soprattutto:

1. Find out your bridge ip address. The most simple way could be checking on your router. 

2. Open http://bridge_ip_address/debug/clip.html. You'll get a simple client. Try stuffs there. 

Dopo aver testato che si può mettere a cambiare nel clip. Quindi torna al tuo codice rapido. Come @nickgraef menzionato nei commenti. L'endpoint dovrebbe essere: http: // bridge_ip_address/api/[nome utente]/luci/2/stato.

Agent.put("http://bridge_ip_address/api/[username]/lights/2/state", headers: [ "Header": "Value" ], 
    data: [ "hue": 35000 ], done: nil) 
1

Esempio con Swift 2

let url = NSURL(string: "https://yourUrl.com") //Remember to put ATS exception if the URL is not https 
    let request = NSMutableURLRequest(URL: url!) 
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") //Optional 
    request.HTTPMethod = "PUT" 
    let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil) 
    let data = "[email protected]&password=password".dataUsingEncoding(NSUTF8StringEncoding) 
    request.HTTPBody = data 

    let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in 

     if error != nil { 

      //handle error 
     } 
     else { 

      let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding) 
      print("Parsed JSON: '\(jsonStr)'") 
     } 
    } 
    dataTask.resume() 
+0

perché non utilizzare un tipo [String: AnyObject] per i dati? –

Problemi correlati