Не работает - регистрация пользователя в Api программно - PullRequest
0 голосов
/ 12 мая 2019

Я пытаюсь зарегистрировать пользователя в своем API.Когда я делаю это в Postman, он регистрирует пользователя и возвращает статус true и сообщение как пользователя, созданного, но когда я пытаюсь программно создать нового пользователя из swift, он всегда возвращает false следующим образом:

["name": "Ilan", "surname": "Usjnda", "email:": 
"ilanaa@mail.ru", "status": "0", "parent_id": "0", "lat": "0", 
"lng": "0", "password": "okpiuh123"]

false

Вот мой полный код о регистрации:

Просмотр контроллера

    import UIKit

    class RegisterViewController: UIViewController {
        var reg : RegView {return self.view as! RegView}

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.interactivePopGestureRecognizer?.isEnabled = true

        reg.reg_button.addTarget(self, action: #selector(register), for: .touchUpInside )
        // Do any additional setup after loading the view.
    }

    override func loadView() {
        super.loadView()
        self.view = RegView(frame: self.view.bounds)
    }
    @objc func register() {
        Register.register(mail: reg.log_textf.text!, password: reg.pass_textf.text!, name: reg.name_textf.text!, surname: reg.surname_textf.text!,lat: "0",lng: "0",parent_id: "0",status: "0")

    } 

Функция регистрации

import Foundation
    import Alamofire
    import SwiftyJSON


class Register {
    class func register(mail:String,password:String,name:String,surname:String,lat:String,lng:String,parent_id:String,status:String) {
        let url = "https://balaqorgau.kz/api/register"
        let header : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
        let params = ["email:":mail,"password":password,"name":name,"surname":surname,"status":status,"parent_id":parent_id,"lat":lat,"lng":lng]
        print(params)        
        Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: header).responseJSON { (response) in
            if response.data != nil {
                switch response.result {
                case.failure(let error):
                    print(error)
                case.success(let val):
                    let json = JSON(val)
                    print(json)
                }
            }
        }
    }
}

Регистрация просмотра

import UIKit

class RegView: UIView {
    var name_textf : UITextField = {
        let button = UITextField()
        button.backgroundColor = .white
        button.placeholder = "Имя"
        button.textAlignment = .center

        button.layer.cornerRadius = 15
        return button
    }()
    var scroll = UIScrollView()
    var surname_textf : UITextField = {
        let button = UITextField()
        button.backgroundColor = .white
        button.placeholder = "Фамилия"
        button.textAlignment = .center

        button.layer.cornerRadius = 15
        return button
    }()
    var log_textf : UITextField = {
        let button = UITextField()
        button.backgroundColor = .white
        button.placeholder = "Email"
        button.textAlignment = .center

        button.layer.cornerRadius = 15
        return button
    }()

    var pass_textf : UITextField = {
        let button = UITextField()
        button.backgroundColor = .white
        button.placeholder = "Пароль"
        button.textAlignment = .center
        button.isSecureTextEntry = true
        button.layer.cornerRadius = 15
        return button
    }()
    var conf_pass_textf : UITextField = {
        let button = UITextField()
        button.backgroundColor = .white
        button.placeholder = "Повторите Пароль"
        button.textAlignment = .center
        button.layer.cornerRadius = 15
        button.isSecureTextEntry = true
        return button
    }()

    var reg_button : UIButton = {
        let button = UIButton()
        button.backgroundColor = #colorLiteral(red: 1, green: 0.6470588235, blue: 0, alpha: 1)
        button.setTitle("Зарегистрироваться", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 15
        return button
    }()

    let icon : UIImageView = {
        let image = UIImageView()
        image.contentMode = .scaleAspectFit
        image.image = #imageLiteral(resourceName: "medet1")
        return image
    }()
    lazy var stack : UIStackView = {
        let stack = UIStackView(arrangedSubviews: [icon,name_textf,surname_textf,log_textf,pass_textf,conf_pass_textf,reg_button])
        stack.axis = .vertical
        stack.distribution = .fill
        stack.spacing = 20
        stack.translatesAutoresizingMaskIntoConstraints = false
        return stack
    }()

    func add() {
        self.backgroundColor = #colorLiteral(red: 0.2862745098, green: 0.7647058824, blue: 0.9607843137, alpha: 1)
        let screensizee = UIScreen.main.bounds
        let width = screensizee.width
        let height = screensizee.height
        scroll = UIScrollView(frame: CGRect(x: 0, y: 0, width: width, height: height))
        self.addSubview(scroll)

        scroll.addSubview(stack)

        stack.snp.makeConstraints { (cons) in
            cons.left.right.equalTo(self).inset(30)
            cons.top.equalTo(scroll).inset(40)
            cons.bottom.equalTo(scroll).inset(100)
        }
        log_textf.snp.makeConstraints { (cons) in
            cons.height.equalTo(50)
        }
        name_textf.snp.makeConstraints { (cons) in
            cons.height.equalTo(50)
        }
        surname_textf.snp.makeConstraints { (cons) in
            cons.height.equalTo(50)
        }
        pass_textf.snp.makeConstraints { (cons) in
            cons.height.equalTo(50)
        }
        conf_pass_textf.snp.makeConstraints { (cons) in
            cons.height.equalTo(50)
        }
        reg_button.snp.makeConstraints { (cons) in
            cons.height.equalTo(50)
        }
        icon.snp.makeConstraints { (cons) in
            cons.width.height.equalTo(150)
        }
        let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
        backgroundImage.image = #imageLiteral(resourceName: "medet")
        backgroundImage.contentMode = .scaleAspectFill
        self.insertSubview(backgroundImage, at: 0)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        add()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

1 Ответ

0 голосов
/ 12 мая 2019

Вы можете попробовать это ниже код:

Обратите внимание на мой параметр заголовка:

let parameters: Parameters = [
            "name"        :   "Ilan"
        ]


        Alamofire.request(apiURLStr, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { responseObject in

            switch responseObject.result {
            case .success:
                let json: JSON = JSON.init(data: responseObject.data!)
                print(json)
            case .failure(let error):
                print(error)

        }
...