Appspot.com API from swift

I'm developing an iOS app that translates Japanese sentences to English using Google Translate API. I could fetch translated data from the API using curl command, but am now having a trouble to fetch data using Swift.

Following is the curl command I used.

curl -X POST \
>   https://XXXXX.appspot.com/api/translate \
>   -H 'Postman-Token: XXXXX' \
>   -H 'cache-control: no-cache' \
>   -H 'content-type: multipart/form-data; boundary=----XXXXX' \
>   -F 'text=私はあなたが好きです。' \
>   -F target_lang=en \
>   -F text_lang=ja

However, following swift code just has nil in result.

        let reqB: [String:Any] = ["text": text, "target_lang": "en", "text_lang": "ja"]
        let reqBody = try? JSONSerialization.data(withJSONObject: reqB)
        guard let reqUrl = URL(string: "https://XXXXX.appspot.com/api/translate") else {
            return
        }

        var req = URLRequest(url: reqUrl)
        req.httpMethod = "POST"
        req.httpBody = reqBody
        req.setValue("XXXXX", forHTTPHeaderField: "Postman-Token")
        req.setValue("no-cache", forHTTPHeaderField: "cache-control")
        req.setValue("multipart/form-data; boundary=----XXXXX", forHTTPHeaderField: "Content-Type")

        let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
        let task = session.dataTask(with: req, completionHandler: {
            (data , response ,error) in
            session.finishTasksAndInvalidate()

Anyone can help me?

1 answer

  • answered 2018-11-09 04:44 いか活き作り

    I resolved this problem by Alamofire4. It seems "multipartFormData" is the key of this problem.

        let reqUrl = "XXX"
        let originalText = sendingText.data(using: .utf8)!
        let targetLang = "en".data(using: .utf8)!
        let textLang = "ja".data(using: .utf8)!
    
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(originalText, withName: "text", mimeType: "text/plain")
                multipartFormData.append(targetLang, withName: "target_lang", mimeType: "text/plain")
                multipartFormData.append(textLang, withName: "text_lang", mimeType: "text/plain")
        }, to: reqUrl) { (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    if !response.result.isSuccess {
                        print("# ERROR")
                    } else {
                        print("# SUCCESS")
                        if let json = response.result.value as? [String: Any], let translatedText = json["translated_text"] as? String {
                            print(translatedText)
    
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }