Wie stelle ich das am besten an?
Xcode und Localhost Request JSON?
Diese Seite verwendet Cookies. Durch die Nutzung unserer Seite erklären Sie sich damit einverstanden, dass wir Cookies setzen. Weitere Informationen
-
-
-
Hier mal ein Beispiel wie es im moment ist
Quellcode
- // Autorization Start
- func startAutorization() {
- // prepare json data
- let json: [String: Any] = ["email": "test@test.de",
- "password": "Test-01."]
- let jsonData = try? JSONSerialization.data(withJSONObject: json)
- // create post request
- let url = URL(string: "http://10.7.101.107:5000/api/login")!
- var request = URLRequest(url: url)
- request.httpMethod = "POST"
- // insert json data to the request
- request.httpBody = jsonData
- let task = URLSession.shared.dataTask(with: request) { data, response, error in
- guard let data = data, error == nil else {
- print(error?.localizedDescription ?? "No data")
- return
- }
- let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
- if let responseJSON = responseJSON as? [String: Any] {
- print(responseJSON)
- }
- }
- task.resume()
- }
- }
-
Dann versuche es doch mal so:
Quellcode
- // Autorization Start
- func startAutorization() {
- // prepare json data
- let json: [String: Any] = ["email": "test@test.de",
- "password": "Test-01."]
- let jsonData = try? JSONSerialization.data(withJSONObject: json)
- // create post request
- let url = URL(string: "http://10.7.101.107:5000/api/login")!
- var request = URLRequest(url: url)
- request.httpMethod = "POST"
- // insert json data to the request
- request.httpBody = jsonData
- let task = URLSession.shared.dataTask(with: request) { data, response, error in
- print(String.init(data:data encoding:utf8))
- print(response)
- print(error)
- guard let data = data, error == nil else {
- print(error?.localizedDescription ?? "No data")
- return
- }
- let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
- if let responseJSON = responseJSON as? [String: Any] {
- print(responseJSON)
- }
- }
- task.resume()
- }
- }
-
So hat es leider auch nicht Funktioniert.
Aber jetzt habe ich die Lösung, deine Tipp (Zitat) war richtig.
MCDan schrieb:
Ich tippe mal, dass im completionHandler error nicht nil ist. Gib doch auch mal response aus und schaue, ob da noch Infos enthalten sind.
Alternativ setze auch mal per setValue(_:forHTTPHeaderField:) den Content-Type auf application/json.
setValue gesetzt
Jetzt Funktioniert die Ausgabe in der Console wie ich das brauche.
jedenfalls bin ich einen Riesen schritt weiter, Danke
PS. bei Interesse kann ich hier die Komplette Methode posten
Gruß -
Nun kommen wir zur nächsten Methode.
von der "Autorization" Methode bekomme ich den gewünschten Apitoken, in der nächsten Methode möchte ich einen "GET" Request an den Server(Lokal-Test) schicken.
Beim App Start wird also eine Autorisierung gemacht aus der ich ein apitoket bekomme, der wird in globale variable gespeichert.
Danach scanne ich das passende QR Code, Inhalt des QR codes ist die MachineID.
Die MachineID ist im Switch Case angelegt.
Aus dem Token + ID wird ein GET Request an den Server geschickt (Dazu gibt es eine API die JSON zurück liefert)
Wenn ich das jetzt mit einem Tool durchspiele bekomme ich den gewünschten JSON zurück
Hier siehe Screenshot zb.
Bildschirmfoto 2018-10-04 um 14.35.15.png
Jetzt zu meinem Problem
Ich habe das ganze in Xcode gemacht, bekomme auch Status 200 (Die Anfrage wurde erfolgreich bearbeitet und das Ergebnis der Anfrage wird in der Antwort übertragen.) wieder.
Aber JSON Antwort nicht in Xcode console .
Beispiel wo ich grade stehe, mein Coding, ist noch nicht clean, evtl auch falsch...
Quellcode
- // Get Machine Data
- func getMachineData (machineId: String) {
- if(self.appDelegate.apiToken != nil && self.appDelegate.apiToken != ""){
- // // prepare json data
- // let json: [String: Any] = ["email": "test@test.de",
- // "password": "Test-01."]
- //
- // let jsonData = try? JSONSerialization.data(withJSONObject: json)
- //
- // // Request Print in Console
- // let responseJSON = try? JSONSerialization.jsonObject(with: jsonData!, options: [])
- // if let responseJSON = responseJSON as? [String: Any] {
- // print(responseJSON)
- // }
- // Create post request
- let url = URL(string: "http://10.7.100.100:5000/api/v1/reweivobject/"+machineId)!
- print(url)
- //let url = URL(string: "http://10.7.100.100:5000/api/test/echo?message=Hello")!
- //print(url)
- //let url = URL(string: "http://10.7.100.100:5000/api/test/time")!
- // print(url)
- var request = URLRequest(url: url)
- request.httpMethod = "GET"
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
- request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
- request.setValue("Bearer "+self.appDelegate.apiToken!, forHTTPHeaderField: "Authorization")
- // insert json data to the request
- // request.httpBody = jsonData
- let config = URLSessionConfiguration.default
- let session = URLSession(configuration: config)
- let task = session.dataTask(with: request) { (responseData, response, responseError) in
- guard responseError == nil else {
- print(responseError!)
- return
- }
- let httpResponse = response as! HTTPURLResponse
- let statusCode = httpResponse.statusCode
- print(statusCode)
- print(response!.description) //(von ? auf !)
- print(responseData!.description) //(von ? auf !)
- let type = httpResponse.allHeaderFields["Content-Type"]
- print("Content-Type", type) // <--- Force Unwrap (!)
- let l = httpResponse.allHeaderFields["Content-Length"]
- print("Content-Length", l) // <--- Force Unwrap (!)
- // APIs usually respond with the data you just sent in your POST request
- if statusCode == 200{
- if let data = responseData { _ = try? JSONSerialization.jsonObject(with: data, options: []) as? [String:Any];
- // let name = json??["name"] as! String
- // let userid = json??["userid"] as! String
- // print(name)
- // print(userid)
- } else {
- print("no readable data received in response")
- }
- } else {
- print("Authentifizierung fehlgeschlagen")}
- }
- task.resume()
- }
- }
<NSHTTPURLResponse: 0x2814ed800> { URL: 10.7.100.100:5000/api/v1/rewei…95-4935-98a7-72b5a68c95bf } { Status Code: 200, Headers {
"Content-Type" = (
"application/json; charset=utf-8"
);
Date = (
"Thu, 04 Oct 2018 13:28:02 GMT"
);
Server = (
Kestrel
);
"Transfer-Encoding" = (
Identity
);
} }
554 bytes
Sollte aber eigentlich den JSON bekommen wie oben im Screenshot vom Tool...
Habt ihr irgendwelche Ideen?Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von jp.graf ()
-
@jp.graf Kurz vorweg: Du benutzt in Deinem Code viel zuviele überflüssige lokale Variablen. 'Variable shadowing' ist da Dein Freund. Außerdem verwendest Du dauernd forced unwrapped optionals, aka !. Das ist ganz böse.
Ich hab mal auf Grundlage Deines Codes eine kompaktere Variante zusammengehackt, die auf einen offen zugänglichen Testserver zugreift. Copy & Paste in ein Playground und es läuft.
Quellcode
- import Foundation
- let url = URL(string: "https://httpbin.org/json")!
- var request = URLRequest(url: url)
- request.httpMethod = "GET"
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
- request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
- func foo() {
- let session = URLSession(configuration: .default)
- let task = session.dataTask(with: request) { (data, response, error) in
- if let error = error {
- print(error)
- return
- }
- guard
- let response = response as? HTTPURLResponse,
- let data = data
- else {
- print("No response or no data!")
- return
- }
- let statusCode = response.statusCode
- // diagnostics
- let responseType = response.allHeaderFields["Content-Type"]
- let responseLength = response.allHeaderFields["Content-Length"]
- print("response code: \(statusCode)")
- print("Content-Type:", responseType ?? "")
- print("Content-Length:", responseLength ?? 0)
- print("Status code:", statusCode)
- switch statusCode {
- case 200:
- guard let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {
- print("could not deserialize the json data!")
- return
- }
- print(json)
- case 300...399:
- print("Redirection")
- case 400...499:
- print("Client error")
- default:
- print("whatever…")
- }
- }
- task.resume()
- }
- foo()
Das iPhone sagt: "Zum Antworten streichen". Wie? Echt Jetzt? Muß ich erst die Wohnung streichen!? -
-
torquato schrieb:
request.httpMethod = "GET"
torquato schrieb:
Ich hab mal auf Grundlage Deines Codes eine kompaktere Variante zusammengehackt, die auf einen offen zugänglichen Testserver zugreift. Copy & Paste in ein Playground und es läuft
Hast du das selbst im Playground getestet? Mit älteren Versionen hat man doch immer noch
und wenn fertig ein gebraucht. Lass mich da aber gern eines besseren belehren^^ -
matz schrieb:
torquato schrieb:
request.httpMethod = "GET"
Ah, OK. Danke. Ich bin mit diesen APis nicht so vertraut. Hab's einfach so vom OP übernommen.
matz schrieb:
torquato schrieb:
Ich hab mal auf Grundlage Deines Codes eine kompaktere Variante zusammengehackt, die auf einen offen zugänglichen Testserver zugreift. Copy & Paste in ein Playground und es läuft
und wenn fertig eingebraucht. Lass mich da aber gern eines besseren belehren^^
Ja. Selber so im Playground geschrieben. Xcode 10.1 beta 1.
Jetzt, wo Du das ansprichst. Stimmt. Das hätte sonst eigentlich nötig sein müssen. Ich hab mich manchmal schon gewundert, bzw. eher geärgert, warum in Xcode 10 ein Playground einfach weiterläuft, anstatt wie gewohnt nach code execution zu stoppen. Jetzt klicke ich, anders als sonst, häufiger auf Stop.
Da scheint in den Xcode 10 Playgrounds etwas grundsätzlich geändert worden zu sein, ich könnte mich aber nicht daran erinnern, davon etwas in den Release Notes gelesen zu haben.
Danke für den Hinweis. Das wäre mir sonst nicht so bewußt geworden.Das iPhone sagt: "Zum Antworten streichen". Wie? Echt Jetzt? Muß ich erst die Wohnung streichen!? -
torquato schrieb:
Da scheint in den Xcode 10 Playgrounds etwas grundsätzlich geändert worden zu sein, ich könnte mich aber nicht daran erinnern, davon etwas in den Release Notes gelesen zu haben.
Danke für den Hinweis. Das wäre mir sonst nicht so bewußt geworden.
-
torquato schrieb:
@jp.graf Kurz vorweg: Du benutzt in Deinem Code viel zuviele überflüssige lokale Variablen. 'Variable shadowing' ist da Dein Freund. Außerdem verwendest Du dauernd forced unwrapped optionals, aka !. Das ist ganz böse.
Ich hab mal auf Grundlage Deines Codes eine kompaktere Variante zusammengehackt, die auf einen offen zugänglichen Testserver zugreift. Copy & Paste in ein Playground und es läuft.
Quellcode
- import Foundation
- let url = URL(string: "https://httpbin.org/json")!
- var request = URLRequest(url: url)
- request.httpMethod = "GET"
- request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
- request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
- func foo() {
- let session = URLSession(configuration: .default)
- let task = session.dataTask(with: request) { (data, response, error) in
- if let error = error {
- print(error)
- return
- }
- guard
- let response = response as? HTTPURLResponse,
- let data = data
- else {
- print("No response or no data!")
- return
- }
- let statusCode = response.statusCode
- // diagnostics
- let responseType = response.allHeaderFields["Content-Type"]
- let responseLength = response.allHeaderFields["Content-Length"]
- print("response code: \(statusCode)")
- print("Content-Type:", responseType ?? "")
- print("Content-Length:", responseLength ?? 0)
- print("Status code:", statusCode)
- switch statusCode {
- case 200:
- guard let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {
- print("could not deserialize the json data!")
- return
- }
- print(json)
- case 300...399:
- print("Redirection")
- case 400...499:
- print("Client error")
- default:
- print("whatever…")
- }
- }
- task.resume()
- }
- foo()
Vielleicht hilft's ja…
Speziell mit dieser URL funktioniert es bei mir in XCODE auch.
Siehe hier:
Quellcode
- // Test GET Request (Funktioniert)
- func Test() {
- //create the url with NSURL
- let url = URL(string: "http://httpbin.org/get")! //change the url
- //create the session object
- let session = URLSession.shared
- //now create the URLRequest object using the url object
- let request = URLRequest(url: url)
- //create dataTask using the session object to send data to the server
- let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
- guard error == nil else {
- return
- }
- guard let data = data else {
- return
- }
- do {
- //create json object from data
- if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
- print(json)
- }
- } catch let error {
- print(error.localizedDescription)
- }
- })
- task.resume()
- }
Mit meiner Test API bin ich jetzt soweit das ich eine JSON Antwort bekomme und in der Console ausgeben kann.
Jetzt muss ich noch rausfinden wie ich auf ein bestimmtes Value innerhalb JSSON zugreifen kann...
So sieht jetzt meine Raw JSON Antwort aus:
Quellcode
- {"error":false,"result":{"id":"bb06424e-a795-4935-98a7-72b5a68c95bf","mandtID":"1e5eaf1a-31e7-4f76-b064-70ee1e2f0280","clientID":null,"name":"Name1","description":"Roboter","type":"KR150","manufacturer":"KUKA","startupDate":"2018-09-03T13:01:43.247499","regNumber":"235/KKD","purchPrice":100000.0,"purchDate":"2018-09-03T13:01:43.247501","serialNumber":234567891,"country":"Germany","place":"Stuttgart","costUnit":"KST 610","warrantyFrom":"2018-09-03T13:01:43.247503","warrantyTo":"2018-09-03T13:01:43.247504","objectDocuments":null,"objectGroups":null}}
-
Dieses JSON sollte Dir ein Dictionary mit den Keys error und result liefern. result ist dann auch ein Dictionary. Wenn Du dazu passende Codable structs erstellst, dann kannst Du die JSON Daten auch direkt in diese structs mappen.
-
Morgen, ja habe es jetzt mit Structs gelöst, funktioniert alles wie gewünscht.
Danke für die sehr guten Tipps
Gruß