使用字典swift将参数发布到服务器 [英] post parameter to sever using dictionary swift

查看:94
本文介绍了使用字典swift将参数发布到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用字典将数据发送到服务器,但遗憾的是数据未保存到数据库(字段被发现为空白),我收到以下回复:

I am trying to send data to the server using a dictionary but unfortunately the data is not saving to the database (fields were found to be blank) and I am getting the below response:


可选([status:true,msg:成功])

Optional(["status": true, "msg": successfull])



<并且还尝试向用户显示 UIActivityIndi​​cator ,直到他得到回复但找不到方法。

And also tried to show UIActivityIndicator to user until he got a response but couldn't find a way.

尝试的代码:

let dict = [ "key_one": self.tf1.text!,"key_two":self.tf2.text!]

    do {

        let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted)

        // create post request
        let url = NSURL(string: "myAPIUrl.php?")!
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"

        // insert json data to the request
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.HTTPBody = jsonData

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
            if error != nil{
                print("Error -> \(error)")
                return
            }

            do {
                let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

                print("Response -> \(result)")

            } catch {
                print("Inside Error Section -> \(error)")
            }
        }

        task.resume()

    } catch {
        print(error)
    }


推荐答案

//写一个fucantion

// write this in one fucantion

 let Username:NSString = EmailTextField.text! as NSString
 let password:NSString = PasswordTextField.text! as NSString


 let headers = [
            "content-type": "application/json",
            "cache-control": "no-cache",
            "postman-token": "121b2f04-d2a4-72b7-a93f-98e3383f9fa0"
        ]
 let parameters = [
            "username": "\(Username)",
            "password": "\(password)"
        ]

 if let postData = (try? JSONSerialization.data(withJSONObject: parameters, options: [])) {

        var request = NSMutableURLRequest(url: URL(string: "YOUR_URL_HERE")!,
                                              cachePolicy: .useProtocolCachePolicy,
                                              timeoutInterval: 10.0)
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody = postData

        let session = URLSession.shared

        let task = URLSession.shared.dataTask(with: request as URLRequest) {
               (data, response, error) -> Void in
                if (error != nil) {
                    print(error)
                } else {
                    DispatchQueue.main.async(execute: {

                      if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? NSDictionary
                        {
                            let success = json["status"] as? Int
                            let message = json["message"] as? String
                            // here you check your success code.
                            if (success == 1)
                            {
                                print(message)
                                let vc = UIActivityViewController(activityItems: [image],  applicationActivities: [])
                                 present(vc, animated: true)
                            }
                            else
                            {

                               // print(message)
                            }

                        }

                    })
                }
            }

            task.resume()
        }

这篇关于使用字典swift将参数发布到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆