android - 使用 NSURLSession 将 Android post 请求转换为 iOS swift

标签 android ios swift http post

我正在尝试将我的 Android 发布请求转换为 iOS (Swift)。目前,这是 Android 代码:

    JSONObject json = new JSONObject();
    json.put("major", Major);
    json.put("minor", Minor);
    json.put("uuid", UUID);
    json.put("userid", id);

    int TIMEOUT_MILLISEC = 10000;  // = 10 seconds

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
    HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
    HttpClient client = new DefaultHttpClient(httpParams);

    HttpPost request = new HttpPost("http://" + ipAddress + ":8080/");
    request.setHeader("Content-Type", "application/json");


    request.setEntity(new ByteArrayEntity(
                json.toString().getBytes("UTF8")));
    HttpResponse response = client.execute(request);

这工作得很好。 但是,当我尝试将它转换为 Swift 时,即使我知道它正在执行请求,服务器也没有收到任何东西。

swift :

            var request = NSMutableURLRequest(URL: NSURL(string: URLString)!)
            var session = NSURLSession.sharedSession()
            request.HTTPMethod = "POST"

            var params = ["major": "1", "minor": "2", "uuid": "00000000-1111-2222-3333-444444444444", "userid": "3"] as Dictionary<String, String>


            request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            let task = session.dataTaskWithRequest(request) { data, response, error in
                guard data != nil else {
                    print("no data found: \(error)")
                    return
                }

                do {
                    if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                        let success = json["success"] as? Int                                  
                    } else {
                        let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)    
                    }
                } catch let parseError {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                }
            }

任何帮助或指导都会很好。谢谢。

编辑 1:一个 task.resume() 得到了服务器的响应。但是,如果有人知道如何转换“request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));"在 Swift 中,这真的很有帮助。

最佳答案

@Naga Krishnamraju 对于您需要将 json 字符串解析为对象的第二个问题,您可以使用以下方式进行操作

      if(response != nil)
            {
                // Print out reponse body
                let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                //print("****** response data = \(responseString!)")

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

                    print(json ?? "Error")
                    print("responseString :-%@",responseString ?? "error");
                    DispatchQueue.main.async {

                        if((json?.count)! > 0)
                        {
                           //here you get json as dictionary now you can have your implementation
                        }

                    }

                }catch
                {
                    print(error)
                    failure(error as NSError);

                }
            }

关于android - 使用 NSURLSession 将 Android post 请求转换为 iOS swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38384007/

相关文章:

java - Android:在 View.setSystemUiVisibility(int) 中读取按位运算符 OR

android - Android 上的 Achartengine - 多个 Y 轴

iOS:部分与 UITableView 记录重叠

ios - 在 Swift 中使用 CommonCrypto 会生成不安全的扩展警告

ios - 如何将 BFTask 与 Swift 3 结合使用?

android - Android 上带图标的弹出菜单

android - 调用 getApplicationContext() 时调用的代码在哪里?

ios - 具有演示样式 formSheet 的模态 UIViewController 在 iPhone XS Max 和 iPhone XR 上显示不正确

ios - 无法从 iOS 7 中的 App Store Receipt 获取 original_application_version

操作系统 |无法更改应用程序委托(delegate)中的 Root View Controller