iOS程序访问服务器-实战篇一

为什么不可以直接用iOS程序直接访问服务器上的数据库?,因为app容易被逆向工程破解,数据库账号密码被获取存在信息安全的问题。 并且,客户端一旦发布出去,没有办法及时修改代码。所以需要一个中间件,所谓的web服务器>

iOS->web服务器->后台
这里完们用的是本地服务器
前提:1、启动apache,2、可以访问php页面,3、安装myql。 USE GOOGLE
如何访问php页面以及出现的问题:https://blog.csdn.net/hkhl_235/article/details/103395449

启动apache

  • sudo apachectl -k start

启动mysql

  • 安装好后可以通过图形界面启动
    iOS程序访问服务器-实战篇一_第1张图片

先玩一下php连接mysql吧
1.先建立数据库
mysql -uroot -p 然后输入密码

//创建数据库
CREATE DATABASE mydb;
CREATE TABLE userInfo(
	id mediumint NOT NULL AUTO_INCREMENT PRIMARY KEY,
    userName varchar(255) NOT NULL DEFAULT '',
    userPwd varchar(255) NOT NULL DEFAULT '',
    sex tinyint NOT NULL DEFAULT 0,
    userImage varchar(255) NOT NULL DEFAULT '',
    location varchar(255) NOT NULL DEFAULT '',
    dscription varchar(255) NOT NULL DEFAULT '',
    birthday varchar(255) NOT NULL DEFAULT '',
    eamil varchar(255) NOT NULL DEFAULT '',
    blog varchar(255) NOT NULL DEFAULT '',
    qq varchar(20) NOT NULL DEFAULT '',
    msn varchar(100) NOT NULL DEFAULT ''
);
INSERT INTO userInfo (userName, userPwd) VALUES ('wuhu', '123456');
INSERT INTO userInfo (userName, userPwd) VALUES ('zhang', '1');
INSERT INTO userInfo (userName, userPwd) VALUES ('lisi', 'li');
INSERT INTO userInfo (userName, userPwd) VALUES ('wangwu', 'wang');

2.php连接mysql

//php访问数据库  database.php

	//连接数据库参数 账号 密码 数据库名
    $connection=mysqli_connect('127.0.0.1', 'root', '12345678', 'mydb');
	mysqli_set_charset($connection, 'utf8');
    if (mysqli_connect_errno()){
            printf("连接错误:%s\n", mysqli_connect_error());
            exit();
    }
    $query=mysqli_query($connection , 'select * from userInfo;');
	if(! $query){
        exit('查询失败');
    }    
    
	//循环查询
	while($row=mysqli_fetch_assoc($query)){
	    var_dump($row);
	    // printf ("%s (%s)\n",$row["id"],$row["userName"]);
	}
	//释放查询结果集
    mysqli_free_result($query);
    //关闭连接
    mysqli_close($connection);
?>

3.通过web访问数据库
如下所示,访问成功
在这里插入图片描述

4.php连接mysql报错
访问数据库报错:The server requested authentication method unknown to the client

查阅一些相关的资料后发现是由于新版本的mysql账号密码解锁机制不一致导致的,解决方法如下:

mysql -uroot -p 
use mysql;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '你的密码';

html访问php
1.后台login.php文件


class itcastUsers {
  private $db;

  // 构造函数-建立数据库链接
  function __construct() {
    //使用mysqli连接数据库, 参数4是数据库名称
    $this->db = new mysqli('127.0.0.1', 'root', '12345678', 'mydb');  

    if (mysqli_connect_errno()){
      printf("连接错误:%s\n", mysqli_connect_error());
      exit();
    }

    $this->db->autocommit(FALSE);
  }

  // 析构函数-关闭数据库连接
  function __destruct() {
    $this->db->close();
  }

  // 用户登录
  function userLogin() {
    if (isset($_GET['username']) && isset($_GET['password'])){
      // 获取GET请求参数
      $accessType = '[GET]';
      $userName = $_GET['username'];
      $userPassword = $_GET['password'];
    } else if (isset($_POST['username']) && isset($_POST['password'])){
      // 获取POST请求参数
      $accessType = '[POST]';
      $userName = $_POST['username'];
      $userPassword = $_POST['password'];

    } else {
      echo('非法请求!');
      return false;
    }

    // 设置数据库查询字符编码
    $this->db->query('set names utf8');

    // 查询请求
    $data = $this->db->query("SELECT id, userName, userImage FROM userInfo WHERE userName='$userName' AND userPwd='$userPassword'");

    // 绑定查询参数
    $this->db->real_escape_string($userName);
    $this->db->real_escape_string($userPassword);

    // 提交查询请求
    $this->db->commit();

    // 提取一条查询结果
    $row = $data->fetch_assoc();
    //var_dump($row);打印结果

    // 将结果绑定到数据字典
    $result = [
      'userId' => $row['id'],
      'userName' => $row['userName'],
      'userImage' => $row['userImage']
    ];
    
    // 将数据字典使用JSON编码
    echo json_encode($result);
    return true;
  }
}

header('Content-Type:text/html;charset=utf-8');
$itcast = new itcastUsers;
$itcast->userLogin();
?>

2.前端html文件

//html



    
    post请求


GET请求



POST请求



iOS程序访问服务器-实战篇一_第2张图片
表单中填写数据库中存储的一组账号密码。点击提交后正常获得数据表示访问成功,
iOS程序访问服务器-实战篇一_第3张图片
创建xcode项目首先设置可以访问http

xcode需要设置可以访问http
文件Info.plist 点击+添加App Transport Security Settings, 点击左边三角,点击+添加Allow Arbitrary Loads,将值改为YES. 不然无法访问http
iOS程序访问服务器-实战篇一_第4张图片

接下来就可以进入正题了-
通过xcode模拟浏览器的get/post请求,去访问后台服务器php提供的接口,获取所需的数据。
stoaryboard的控件
iOS程序访问服务器-实战篇一_第5张图片
ViewController.m

@interface ViewController ()
@property (nonatomic, weak) IBOutlet UITextField *userName;
@property (nonatomic, weak) IBOutlet UITextField *userPwd;  
@property (nonatomic, weak) IBOutlet UILabel *logonLabel;    
@property (nonatomic, weak) IBOutlet UIButton *logon;
-(IBAction)logClk:(id)sender;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}


- (void)postFunc {
    //登录完成前不能做其他操作
    //登录操作异步执行 不会影响到其他操作。
    NSString *str = [NSString stringWithFormat:@"http://localhost/login.php"];
    NSURL *urlStr = [NSURL URLWithString:str];
    
    //psot需要另外的request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlStr];
    request.HTTPMethod = @"POST";
    
    //数据体
    //{"userId":"2","userName":"zhang","userImage":""}
    NSString *string = [NSString stringWithFormat:@"username=%@&password=%@", self.userName.text, self.userPwd.text];
    //将字符串转换为二进制数据
    request.HTTPBody = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil) {
            //将二进制数据data转换为data
            NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            
            //打印数据
            NSLog(@"%@  %@", string, [NSThread currentThread]);
            
            //内部阻塞进行操作主线程更新画ui
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                self.logonLabel.text = @"登录完成";
            }];
        }
    }];
    
    //外部登录不影响其他异步操作
    NSLog(@"main thread...");
}

- (void)getFunc {
    //登录完成前不能做其他操作
    //登录操作异步执行 不会影响到其他操作。
    NSString *str = [NSString stringWithFormat:@"http://localhost/login.php?username=%@&password=%@", self.userName.text, self.userPwd.text];
    NSURL *urlStr = [NSURL URLWithString:str];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:urlStr];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil) {
            //将二进制数据data转换为data
            NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            
            //打印数据
            NSLog(@"%@  %@", string, [NSThread currentThread]);
            
            //内部阻塞进行操作主线程更新画ui
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                self.logonLabel.text = @"登录完成";
            }];
        }
    }];
    
    //外部登录不影响其他异步操作
    NSLog(@"main thread...");
}

//点击登录 触发get/post函数,获取网路请求;
-(IBAction)logClk:(id)sender {

    [self postFunc];
}

运行后输入账号密码,点击登录-  可以获取服务器返回的数据
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191208141030285.png)

你可能感兴趣的:(iOS)