post parameter to sever using dictionary swift

耗尽温柔 提交于 2019-12-02 10:28:09

// 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()
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!