我正试图使用字典将数据发送到服务器,但不幸的是,数据没有保存到数据库(发现字段为空),我得到以下响应:
可选([“status”:true,“msg”:successfull])
还尝试向用户显示UIActivityIndicator,直到他得到响应,但找不到方法。
尝试的代码:

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)
    }

最佳答案

//把这个写在一个函数里

 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()
        }

10-06 01:31