ios - Post 方法不在 api 调用中发送我的数据

标签 ios swift post httprequest swifty-json

您好,我是 swift 的新手,我进行了以下 api 调用或发送数据,但它没有发送,我得到了以下响应。

发送数据

firstName=gggg&lastName=ggg&username=fgg&password=ghh&email=ggg@gg.com&latitude=25.0710693470323&longitude=55.143004052641

回应

responseString  {"status":"error","message":"Oops!!!Something went wrong..."}

但我可以获得所有其他验证消息,例如“用户名不能为空”。

但我尝试使用 Postman 它也给出了与上面关于 header 方法相同的错误消息,但后来我想出了并发送了 Body 方法和 application/x-www-form-urlencoded 的形式,然后我得到了如下成功响应。

enter image description here

以下是我的 API 调用...请有人找出我做错了什么或建议我更好的 post api 调用。

还有一件事,这是我为“/homefeed”创建的相同 API 调用方法并获得了响应,但我们不需要为此发送任何特定参数。请帮助我。

 func addNewUser()
    {
        let url = URL(string: "https://xxxxxxxxxx.azurewebsites.net/api/addUser")!

        let firstName:String = firstnameTextFeild.text!
        let lastName:String = lastNameTxtField.text!
        let username:String = usernameTextField.text!
        let password:String = passwordTextField.text!
        let email:String = emailTextField.text!
        var request = URLRequest(url: url)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        let postString = "firstName=\(firstName)&lastName=\(lastName)&username=\(username)&password=\(password)&email=\(email)&latitude=\(lat)&longitude=\(long)"
        print("Sent Data -",postString)
        request.httpBody = postString.data(using: .utf8)
        /*
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body

        } catch let error {
            print(error.localizedDescription)
        }
       */
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }

            let responseString = String(data: data, encoding: .utf8)

            // print("responseString = \(String(describing: responseString))")
            print("responseString ", responseString ?? "resSt")


        }
        task.resume()

    }

最佳答案

使用此代码。它对您有用。

安装pod文件

pod 'Alamofire'

在您的 ViewController 中导入 Alamofire

func addNewUser(){
let url = "your URL"
var param : [String : AnyObject] = [:]

param = ["firstName": firstnameTextFeild.text! as AnyObject,
         "lastName": lastNameTxtField.text! as AnyObject,
         "username": usernameTextField.text! as AnyObject,
         "password": passwordTextField.text! as AnyObject,
         "email": emailTextField.text! as AnyObject,
         "latitude": "your latitude" as AnyObject,
         "longitude": "your longitude" as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
    print(response)

    if (response.result.value != nil) {
        //your code
    }
    else{
        //your code
    }
  }
}

关于ios - Post 方法不在 api 调用中发送我的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49994868/

相关文章:

javascript - Cakephp:使用 javascript 时按钮的名称不包含在帖子中

ios - 每当我尝试使用 rangeOfString 时,它都会说在 UITextView 中找不到成员

ios - NSOperationQueue,并发操作和线程

ios - 为什么选择其他分割后iOS分割控件的颜色无法恢复

ios - 从 iPhone 加载联系人在 Swift 中崩溃

swift - 环境变量未传递给 subview

api - 为什么我的 POST 请求仅对我的 API 不起作用?

ios - 当模型应该在启动后不久就开始某些事件时,iOS 中的规范设计模式/构造是什么?

ios - 我从 NSUserDefaults 得到的对象(字典)有问题

ios - 如何使用以下方法发帖 这里