Reputation: 17
i'm trying to find a solution for 2 days already. Have made http request, i can see in view that server response, but it's not what I expect. The server says I'm sending an empty request. Maybe there's something obvious here that I can't notice?
Here is my code:
public class Api: ObservableObject { @Published var get: String = "none"
init()
{
getSongs()
}
func getSongs()
{
let url = URL(string: "http://31.31.196.187:5000/search")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
let postString:[String:Any] = [
"song_url": "https://music.yandex.ru/album/4066489/track/33274678",
"service": "Spotify"
]
let jsonData = try? JSONSerialization.data(withJSONObject: postString, options: JSONSerialization.WritingOptions())
request.httpBody = jsonData
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else
{
print ("Error!!!")
return
}
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:\n \(dataString)")
self.get = dataString
}
} .resume()
}
}
Upvotes: 0
Views: 361
Reputation: 17
I just added this simple command and it start working.
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
Sometimes you just need to ask a question to find the answer!
Upvotes: 1