2016-09-25 8 views
5

Muszę przekazać następujący json do tej funkcji, aby Shopify Api mógł zrozumieć zgłoszenie.swift 3 Postój parametru json do api

Za każdym razem, gdy wykonuję ten kod, pojawia się komunikat o błędzie, że brakuje wymaganego parametru. Oczywiście nie jestem w stanie stworzyć poprawnego formatu zmiennej i przekazać go serwerowi.

Shopify API spodziewa następujący json być przekazywane za pośrednictwem POST

{ 
    "customer": { 
     "first_name": "Steve", 
     "last_name": "Lastnameson", 
     "email": "[email protected]", 
     "verified_email": true, 
     "addresses": [ 
      { 
       "address1": "123 Oak St", 
       "city": "Ottawa", 
       "province": "ON", 
       "phone": "555-1212", 
       "zip": "123 ABC", 
       "last_name": "Lastnameson", 
       "first_name": "Mother", 
       "country": "CA" 
      } 
     ] 
    } 
} 

Oto mój kod wpis:

let customer = [ 
    "customer": [ 
     "first_name": "Steve", 
     "last_name": "Lastnameson", 
     "email": "[email protected]", 
     "verified_email": "true", 
     "addresses": [ 
      [ 
       "address1": "123 Oak St", 
       "city": "Ottawa", 
       "province": "ON", 
       "phone": "555-1212", 
       "zip": "123 ABC", 
       "last_name": "Lastnameson", 
       "first_name": "Mother", 
       "country": "CA", 
      ], 
     ], 
    ], 
] as [String: Any] 

var request = URLRequest(url: URL(string: shopUrl + "/admin/customers.json")!) 
request.httpMethod = "POST" 
request.httpBody = try! JSONSerialization.data(withJSONObject: customer, options: []) 

URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in 
    if error != nil { 
     print(error) 
    } else { 
     do { 
      guard let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] else { return } 

      guard let errors = json?["errors"] as? [[String: Any]] else { return } 
       if errors.count > 0 { 
        // show error 
        return 
       } else { 
        // show confirmation 
       } 
      } 
     } 
    }).resume() 
+0

Jaka jest dokładna odpowiedź, którą otrzymujesz z serwera? –

+1

do utworzenia nowego konta klienta – Hamid

+0

Problem polega na tym, że serwer nie otrzymuje danych w oczekiwanym formacie. – Hamid

Odpowiedz

5

Żądanie musi mieć typ zawartości zadeklarowana. Dodaj:

request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
request.addValue("application/json", forHTTPHeaderField: "Accept")