Ios 不工作-在Swift 3/4中以编程方式在Api中注册用户
我正在尝试在API中注册一个用户。当我在Postman中这样做时,它会注册用户并返回状态为true,返回消息为user Created,但当我尝试通过编程从swift创建新用户时,它总是显示用户已经存在(给出错误响应),即使它没有注册。我使用的是Swift 4 Xcode 9 几乎相同的代码适用于登录Api,但不适用于用户注册。另外,在我通过Api中的postman注册了该用户之后,它的登录效果非常好。所以我不明白RegisterUser有什么问题。代码显示没有错误 以下是我的registeringUser代码:Ios 不工作-在Swift 3/4中以编程方式在Api中注册用户,ios,swift,api,alamofire,Ios,Swift,Api,Alamofire,我正在尝试在API中注册一个用户。当我在Postman中这样做时,它会注册用户并返回状态为true,返回消息为user Created,但当我尝试通过编程从swift创建新用户时,它总是显示用户已经存在(给出错误响应),即使它没有注册。我使用的是Swift 4 Xcode 9 几乎相同的代码适用于登录Api,但不适用于用户注册。另外,在我通过Api中的postman注册了该用户之后,它的登录效果非常好。所以我不明白RegisterUser有什么问题。代码显示没有错误 以下是我的registeri
import UIKit
import SwiftyJSON
import Alamofire
import SwiftKeychainWrapper
class RegisterUserViewController: UIViewController {
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var emailAddressTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var repeatPasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancelButtonTapped(_ sender: Any) {
print("Cancel button tapped")
self.dismiss(animated: true, completion: nil)
}
@IBAction func signupButtonTapped(_ sender: Any) {
print("Sign up button tapped")
// Validate required fields are not empty
if (firstNameTextField.text?.isEmpty)! ||
(lastNameTextField.text?.isEmpty)! ||
(emailAddressTextField.text?.isEmpty)! ||
(passwordTextField.text?.isEmpty)!
{
// Display Alert message and return
displayMessage(userMessage: "All fields are quired to fill in")
return
}
// Validate password
if ((passwordTextField.text?.elementsEqual(repeatPasswordTextField.text!))! != true)
{
// Display alert message and return
displayMessage(userMessage: "Please make sure that passwords match")
return
}
let userdefault = UserDefaults.standard
userdefault.set(emailAddressTextField.text, forKey: "email_id")
//userdefault.set(emailAddressTextField, forKey: "email_id")
print("email_id",emailAddressTextField.text)
//print("email_address",userdefault.string(forKey: "email_id"))
var request = URLRequest(url: URL(string: "http://horn.hostingduty.com/api/v1/app_adduser")!)
request.httpMethod = "POST"
print("its working")
let postString = "first_name=\(firstNameTextField.text)";
"last_name=\(lastNameTextField.text)";
"email_id=\(emailAddressTextField.text)";
"password=\(passwordTextField.text)"
request.httpBody = postString.data(using: .utf8)
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=\(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 = \(response)")
}
var responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
if(responseString?.contains("true"))!{
DispatchQueue.main.async
{
let homePage = self.storyboard?.instantiateViewController(withIdentifier: "HomePageViewController") as! SWRevealViewController
let appDelegate = UIApplication.shared.delegate
appDelegate?.window??.rootViewController = homePage
}
print("status = true")
}
else{
DispatchQueue.main.async
{
self.showToast(message: "Already exists !! ")
}
print("Status = false")
}
}
task.resume()
}
func displayMessage(userMessage:String) -> Void {
DispatchQueue.main.async
{}
let alertController = UIAlertController(title: "Alert", message: userMessage, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
// Code in this block will trigger when OK button tapped.
print("Ok button tapped")
DispatchQueue.main.async
{
self.dismiss(animated: true, completion: nil)
}
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion:nil)
}
}
您应该向请求添加标题,并发送正确的url编码键/值
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type");
并将您的帖子字符串更改为
let postString = "first_name=\(firstNameTextField.text)&" +
"last_name=\(lastNameTextField.text)&" +
"email_id=\(emailAddressTextField.text)&" +
"password=\(passwordTextField.text)"
request.httpBody = postString.data(using: .utf8)
更新
func callApi(){
var request = URLRequest(url: URL(string: "http://horn.hostingduty.com/api/v1/app_adduser")!)
request.httpMethod = "post"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
print("its working")
let postString = "first_name=test&" +
"last_name=test&" +
"email_id=test@abc.vom&" +
"password=123&"
request.httpBody = postString.data(using: .utf8)
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=\(error?.localizedDescription)")
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 = \(response)")
}
var responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
if(responseString?.contains("true"))!{
print("status = true")
}
else{
print("Status = false")
}
}
task.resume()
}
poststring声明错误这是什么类型的内容?是表单编码还是Json?encoded@fahadsk您能发布正确的声明吗@但是这看起来和我的代码完全不同。我的代码有什么问题吗?因为它不会给出任何错误,并且可以与登录一起使用。这是登录或注册的答案吗?因为有更多的参数可以注册。或者两者都可以/u可以在参数中传递更多参数这两个代码都是正确的区别在于我使用的是Alamofire,而您使用的是urlsession来传递api。你在项目中使用了Alamofire吊舱,这就是我给出这个答案的原因。使用alamofire比使用urlsessionwelcome容易得多。如果您对我的代码有任何问题,请告诉我,谢谢您的帮助。我像你说的那样更改了代码,但仍然没有成功。我必须复制粘贴你提供的request.setValue,因为它是正确的?你得到了什么错误?尝试打印您的错误和响应值。我没有收到任何错误。它应该将响应设置为true,并将消息设置为“user created”,但每次都只会将响应设置为false,并将消息设置为“user ready exists”(在api中设置),以私有有效的用户设置。“注册”按钮点击电子邮件\u id可选(“hihi@gmail.com)其工作响应字符串=可选(“{”状态\“:\”错误“,\”消息\“:\”抱歉:-(此电子邮件ID已存在…!!\“}”)状态=错误您是否尝试过任何其他电子邮件ID?这也是您以前遇到的错误吗?
func callApi(){
var request = URLRequest(url: URL(string: "http://horn.hostingduty.com/api/v1/app_adduser")!)
request.httpMethod = "post"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
print("its working")
let postString = "first_name=test&" +
"last_name=test&" +
"email_id=test@abc.vom&" +
"password=123&"
request.httpBody = postString.data(using: .utf8)
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=\(error?.localizedDescription)")
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 = \(response)")
}
var responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
if(responseString?.contains("true"))!{
print("status = true")
}
else{
print("Status = false")
}
}
task.resume()
}