XCode, используя CodeIgniter Framework loginAPI (ВНЕШНЕЕ ЗАКРЫТИЕ ПРИЛОЖЕНИЯ)

Я создал свой собственный API для входа и вот он.

Контроллер / API / Authentication.php

<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

// Load the Rest Controller library
require APPPATH . '/libraries/REST_Controller.php';
require APPPATH . '/libraries/Format.php';

use Restserver\Libraries\REST_Controller;

class Authentication extends REST_Controller {

public function __construct() {
parent::__construct();

// Load the user model
$this->load->model('user');
}

public function login_post() {
// Get the post data
$email = $this->post('email');
$password = $this->post('password');

// Validate the post data
if(!empty($email) && !empty($password)){

// Check if any user exists with the given credentials
$con['returnType'] = 'single';
$con['conditions'] = array(
'email' => $email,
'password' => md5($password),
'status' => 1
);
$user = $this->user->getRows($con);

if($user){
// Set the response and exit
$this->response([
'status' => TRUE,
'message' => 'User login successful.',
'data' => $user
], REST_Controller::HTTP_OK);
}else{
// Set the response and exit
//BAD_REQUEST (400) being the HTTP response code
$this->response("Wrong email or password.", REST_Controller::HTTP_BAD_REQUEST);
}
}else{
// Set the response and exit
$this->response("Provide email and password.", REST_Controller::HTTP_BAD_REQUEST);
}
}

public function registration_post() {
// Get the post data
$first_name = strip_tags($this->post('first_name'));
$last_name = strip_tags($this->post('last_name'));
$email = strip_tags($this->post('email'));
$password = $this->post('password');
$phone = strip_tags($this->post('phone'));

// Validate the post data
if(!empty($first_name) && !empty($last_name) && !empty($email) && !empty($password)){

// Check if the given email already exists
$con['returnType'] = 'count';
$con['conditions'] = array(
'email' => $email,
);
$userCount = $this->user->getRows($con);

if($userCount > 0){
// Set the response and exit
$this->response("The given email already exists.", REST_Controller::HTTP_BAD_REQUEST);
}else{
// Insert user data
$userData = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'password' => md5($password),
'phone' => $phone
);
$insert = $this->user->insert($userData);

// Check if the user data is inserted
if($insert){
// Set the response and exit
$this->response([
'status' => TRUE,
'message' => 'The user has been added successfully.',
'data' => $insert
], REST_Controller::HTTP_OK);
}else{
// Set the response and exit
$this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);
}
}
}else{
// Set the response and exit
$this->response("Provide complete user info to add.", REST_Controller::HTTP_BAD_REQUEST);
}
}

public function user_get($id = 0) {
// Returns all the users data if the id not specified,
// Otherwise, a single user will be returned.
$con = $id?array('id' => $id):'';
$users = $this->user->getRows($con);

// Check if the user data exists
if(!empty($users)){
// Set the response and exit
//OK (200) being the HTTP response code
$this->response($users, REST_Controller::HTTP_OK);
}else{
// Set the response and exit
//NOT_FOUND (404) being the HTTP response code
$this->response([
'status' => FALSE,
'message' => 'No user was found.'
], REST_Controller::HTTP_NOT_FOUND);
}
}

public function user_put() {
$id = $this->put('id');

// Get the post data
$first_name = strip_tags($this->put('first_name'));
$last_name = strip_tags($this->put('last_name'));
$email = strip_tags($this->put('email'));
$password = $this->put('password');
$phone = strip_tags($this->put('phone'));

// Validate the post data
if(!empty($id) && (!empty($first_name) || !empty($last_name) || !empty($email) || !empty($password) || !empty($phone))){
// Update user's account data
$userData = array();
if(!empty($first_name)){
$userData['first_name'] = $first_name;
}
if(!empty($last_name)){
$userData['last_name'] = $last_name;
}
if(!empty($email)){
$userData['email'] = $email;
}
if(!empty($password)){
$userData['password'] = md5($password);
}
if(!empty($phone)){
$userData['phone'] = $phone;
}
$update = $this->user->update($userData, $id);

// Check if the user data is updated
if($update){
// Set the response and exit
$this->response([
'status' => TRUE,
'message' => 'The user info has been updated successfully.'
], REST_Controller::HTTP_OK);
}else{
// Set the response and exit
$this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);
}
}else{
// Set the response and exit
$this->response("Provide at least one user info to update.", REST_Controller::HTTP_BAD_REQUEST);
}
}
}
?>

и на моем

Модели / User.php

<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Model {

public function __construct() {
parent::__construct();

// Load the database library
$this->load->database();

$this->userTbl = 'users';
}

/*
* Get rows from the users table
*/
function getRows($params = array()){
$this->db->select('*');
$this->db->from($this->userTbl);

//fetch data by conditions
if(array_key_exists("conditions",$params)){
foreach($params['conditions'] as $key => $value){
$this->db->where($key,$value);
}
}

if(array_key_exists("id",$params)){
$this->db->where('id',$params['id']);
$query = $this->db->get();
$result = $query->row_array();
}else{
//set start and limit
if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit'],$params['start']);
}elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit']);
}

if(array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
$result = $this->db->count_all_results();
}elseif(array_key_exists("returnType",$params) && $params['returnType'] == 'single'){
$query = $this->db->get();
$result = ($query->num_rows() > 0)?$query->row_array():false;
}else{
$query = $this->db->get();
$result = ($query->num_rows() > 0)?$query->result_array():false;
}
}

//return fetched data
return $result;
}

/*
* Insert user data
*/
public function insert($data){
//add created and modified date if not exists
if(!array_key_exists("created", $data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists("modified", $data)){
$data['modified'] = date("Y-m-d H:i:s");
}

//insert user data to users table
$insert = $this->db->insert($this->userTbl, $data);

//return the status
return $insert?$this->db->insert_id():false;
}

/*
* Update user data
*/
public function update($data, $id){
//add modified date if not exists
if(!array_key_exists('modified', $data)){
$data['modified'] = date("Y-m-d H:i:s");
}

//update user data in users table
$update = $this->db->update($this->userTbl, $data, array('id'=>$id));

//return the status
return $update?true:false;
}

/*
* Delete user data
*/
public function delete($id){
//update user from users table
$delete = $this->db->delete('users',array('id'=>$id));
//return the status
return $delete?true:false;
}
}
?>

Теперь на моем XCODE я пытаюсь подключиться из xcode к API входа в систему, тогда нет проблем, фактически он может успешно войти в систему, но мое приложение закрывается без каких-либо ошибок после отправки моего запроса на публикацию.

Я подозреваю, что это из-за basic_auth?

введите описание изображения здесь

или нет

вот мой исходный код на XCODE

@IBAction func buttonLogin(_ sender: UIButton)
{
//getting the username and password
let parameters: Parameters=[
"email": usernameTextField.text!,
"password": passwordTextField.text!,
"X-API-KEY": "xxxx-2018"]

//making a post request
Alamofire.request(URL_USER_LOGIN, method: .post, parameters:parameters).responseJSON{
response in
//printing response
print(response)

//getting the json value from the server
if let result = response.result.value{
let jsonData = result as! NSDictionary
//if there is no error
if(!(jsonData.value(forKey:"error") as! Bool)){
//getting the user from response
//get the user from response
let user = jsonData.value(forKey: "user") as! NSDictionary
//getting user values
let userId = user.value(forKey: "id") as! Int
let userFirstName = user.value(forKey: "first_name") as! String
let userLastName = user.value(forKey: "last_name") as! String
let userEmail = user.value(forKey: "email") as! String
let userPhone = user.value(forKey: "phone") as! String

//saving user values to defaults
self.defaultValues.set(userId, forKey: "userid")
self.defaultValues.set(userFirstName, forKey: "firstname");
self.defaultValues.set(userLastName, forKey: "lastname");
self.defaultValues.set(userEmail, forKey: "useremail")
self.defaultValues.set(userPhone, forKey: "userphone")

//switching the screen
let profileViewController = self.storyboard?.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
self.navigationController?.pushViewController(profileViewController, animated: true)
self.dismiss(animated: false, completion:nil)
}
else
{
//error message in case of invalud credential
//self.labelMessage.text = "Invalid username or password"self.showToast(message:"Invalid username or password!")
}
}
}
}

РЕДАКТИРОВАНИЕ: Итак, я узнал, что basic_auth не был причиной закрытия моего приложения. Я догадываюсь снова, что это мой API?

ДОБАВЬТЕ ИНФОРМАЦИЮ:

введите описание изображения здесь

0

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]