0
class TranslateModel : ObservableObject {
    
    func translateCall() {
        guard let url = URL(string: "https://openapi.naver.com/v1/papago/n2mt") else { return }
        print(1)
        
        let param = "source=en&target=kr&text=hi"
        let paramData = param.data(using: .utf8)
        
        var request = URLRequest(url: url)
        print(2)
        
        request.httpMethod = "POST"
        request.httpBody = paramData
        print(3)
        
        request.addValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.addValue("3Bwy8lMkuAgZOyDHm1Z3", forHTTPHeaderField: "X-Naver-Client-Id")
        request.addValue("gg391Jc1Ge", forHTTPHeaderField: "X-Naver-Client-Secret")
        print(4)
        
        let data = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data else { fatalError() }
            print(5)
            
            guard error == nil else { fatalError()}
            print(6)
            
            guard let response = response as? HTTPURLResponse, response.statusCode >= 200 && response.statusCode < 300 else {return}
            print(7)
            
            print(data)
        }
    }
}

Xcode screenshot

Firstly, Please check my code and screenshot.

I tried to do POST API with parameters and headers. However, when I call the method, It's not working.

So, I checked the step of method, And found that the URLsession with request was not working.

But, I don't know what the problem is.

I think maybe parameters or headers faults. could you let me know how I can solve this?

Sandeep
  • 20,908
  • 7
  • 66
  • 106
Kyungyun Lee
  • 115
  • 9
  • See https://stackoverflow.com/a/26365148/1271826 for example of how to build a x-www-form-urlencoded request. Note, the `resume()` call. BTW, I'd suggest percent encoding, as shown in that answer, because sometimes the string to be translated won't be as simple as “hi”, but might contain reserved characters, such as space, and that answer shows you how to property encode the request. – Rob Mar 07 '22 at 23:30
  • Oh, Thank you so much, but sadly, I think i failed that api cal. I need to find the solution more, thank you! – Kyungyun Lee Mar 09 '22 at 22:08
  • Yeah, `kr` does not appear to be an accepted language code. – Rob Mar 09 '22 at 22:28
  • Just parse the body of the response and it will tell your exactly what is wrong… – Rob Mar 09 '22 at 23:22

0 Answers0