2016-11-18 39 views
9

Uygulamamda json verileriyle http post isteği yapmaya çalışıyorum. Aşağıdaki jsonSwift3'te JSON POST isteği gönderiliyor

{ 
"Password":"123456", 
"Email":"[email protected]" 
} 

API transfer edilmelidir İşte bu görev

let dict = ["Email": "[email protected]", "Password":"123456"] as [String: Any] 
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) { 


    let url = NSURL(string: "http://xxxxxxxxx.net/api/Login")! 
    let request = NSMutableURLRequest(url: url as URL) 
    request.httpMethod = "POST" 

    request.httpBody = jsonData 

    let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in 
     if error != nil{ 
      print(error?.localizedDescription) 
      return 
     } 

     do { 
      let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary 

      if let parseJSON = json { 
        let resultValue:String = parseJSON["success"] as! String; 
        print("result: \(resultValue)") 
        print(parseJSON) 
        } 
      } catch let error as NSError { 
       print(error) 
      }   
     }   
    task.resume() 
    } 

aşağıdaki hatayı

Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.} 

tepki verileri boş alıyorum benim kodudur. Ne yapıyorum ya da kodumda bir şey mi özledim?

İlk:: Veri JSON dönüştürülür eğer

jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) 

sonra günlükleri eklemek

+1

Baskı (yanıt) ve yazdırma (json) 'nin sonucu nedir? – Moritz

+0

yazdırma (yanıt) sonucu İsteğe bağlı ( {URL: http://xxxxxxxxx.net/api/Login} {durum kodu: 415, başlıklar { "İçerik Uzunluğu" = 0; Tarih = "Cum, 18 Kas 2016 12:20:21 GMT"; Sunucu = "Microsoft-IIS/8.0"; "Set-Cookie" = "ARRAffinity = 173cb9da56ba660395def768bf42f0686b2eba6731b99a6d8f2d08471ce133ed; Yol = /; Domain = plubmeradmin.azurewebsites.net "; " X-Powered-By "=" ASP.NET "; }}) ancak yazdırma (json) boş –

+0

Cevabınız:' "Content-Length '= 0'. Sunucu tarafından verilen veriler boş. Ayrıca, [bu Soru-Cevap] 'a bir göz atın (http://stackoverflow.com/questions/22566433/http-415-unsupported-media-type-error-with-json). – Moritz

cevap

16

iki şey deneyin. Verilerinizi String'e dönüştürün ve değeri yazdırın.

Ayrıca httpBody önce

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

ekleyin. Bazen sunucumuza JSON verilerini yayınladığımızı söylememiz gerekiyor.

Bu yardımcı olur umarım!

Mutlu Kodlama!

+0

ile çalışın Çok işe yarıyor –