How to send a POST request through Swift?

前端 未结 3 1887
面向向阳花
面向向阳花 2020-12-25 08:42

I have my controller like this -

def create
   if (@user = User.find_by_email(params[:email])) && @user.valid_password?(params[:password])
      ren         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-25 09:06

    Here is the Example of POST API for calling Login API with parameters "emailaddress" and "password" with userEmailID and Userpassword as two strings holding values for email and password respectively.

    You can call this POST API anywhere in your view controller, as given below:

    self.postLoginCall(url: "Your post method url") example: self.postLoginCall(url: "http://1.0.0.1/api/login.php")

    func postLoginCall(url : String){
    
    
        let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
        request.httpMethod = "POST"
        let postString = "emailaddress=\(userEmailID!)&password=\(Userpassword!)"
        print(postString)
        request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.httpBody = postString.data(using: String.Encoding.utf8)
    
        let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
            guard error == nil && data != nil else {                                                          // check for fundamental networking error
                print("error=\(error)")
                return
            }
    
            do {
            if let responseJSON = try JSONSerialization.jsonObject(with: data!) as? [String:AnyObject]{
                print(responseJSON)
                print(responseJSON["status"]!)
    
    
                self.response1 = responseJSON["status"]! as! Int
    
                print(self.response1)
    
                //Check response from the sever
                if self.response1 == 200
                {
                    OperationQueue.main.addOperation {
    
                        //API call Successful and can perform other operatios
                       print("Login Successful")
                    }
    
                }
    
                else
                {
                    OperationQueue.main.addOperation {
    
                        //API call failed and perform other operations
                        print("Login Failed")
    
                    }
    
                }
    
    
            }
            }
            catch {
                print("Error -> \(error)")
            }
    
    
    
        }
    
    
        task.resume()
    
    
    
    }
    

提交回复
热议问题