iOS学习03

53章

数据持久

应用程序数据持久化。


1、数据库网络获得沙盒SanBox路径

创建视图应用程序

image-20220602110623761

获得沙盒路径,即手机上的路径

//AppDelegate.m
@interface
-(IBAction)homeTap:(id)sender;
@property(weak,nonatomic)IBOutlet UITextView * msgText;
//ViewController.m
-(void)viewDidLoad{
    [super viewDidLoad];
    NSString * path=NSHomeDirectory();
    path=[path stringByAppendingPathComponent:@"abc.txt"];
    NSLog(@"%@",path);
    
    NSString * str=@"1234";
    //[str writeToFile:@"abc.txt" atomically:YES];//用这种方式创建不了沙盒路径下的文件
    [str writeToFile:path atomically:YES];//在应用程序可执行文件路径下写入文件
}
-(IBAction)homeTap:(id)sender{
    //NSLog(@"xxxx")
    self.msgText.text=NSHomeDirectory();
}

2、应用程序路径的变化。

//ViewController.m
-(void)viewDidLoad{
    [super viewDidLoad];
    //NSString * path=NSHomeDirectory();//每运行一次都在改变,有潜在危险,一般只读
    //NSLog(@"%@",path);
    NSArray * paths=NSSearchPathForDirectioriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString * documentsDirectory=[paths objectAtIndex:0];
    NSLog(@"%@",documentsDirectory);
    NSString * filePath=[documentsDirectory stringByAppendingPathComponent:@"aa.txt"];
    /*
    NSString * str=@"12345";
    if([str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil]){
        NSLog(@"创建成功");
    }
    else{
        NSLog(@"创建失败");
    }
    */
    NSString * str=[NSStirng stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",str);
}

3、数据库网络plist文件保存

image-20220602171850207

按住option复制一个按钮

@interface
-(IBAction)homeTap:(id)sender;
@property(weak,nonatomic)IBOutlet UITextView * msgText;
-(IBAction)docTap:(id)sender;
-(IBAction)libTap:(id)sender;
-(IBAction)tmpTap:(id)sender;
//ViewController.m
-(void)viewDidLoad{
    [super viewDidLoad];
    NSString * path=NSHomeDirectory();
    path=[path stringByAppendingPathComponent:@"abc.plist"];//abc.txt
    /*
    NSLog(@"%@",path);
    NSString * str=@"1234";
    //[str writeToFile:@"abc.txt" atomically:YES];//用这种方式创建不了沙盒路径下的文件
    [str writeToFile:path atomically:YES];//在应用程序可执行文件路径下写入文件
    
    //除了上述文件方式保存数据外,还可以采用集合方式
    NSArray * array=[NSArray arrayWithObjects:@"1",@"2",@"33",nil];
    [array writeToFile:path atomically:YES];
    */
    NSDictionary * dict=[NSDictionary dictionaryWithObjectsAndKeys:@"张",@"name",@"12",@"age",nil];
    [dict writeToFile:path atomically:YES];
    //写文件时如果是自定义的类,则需要进行归档处理
    
}
-(IBAction)homeTap:(id)sender{
    //NSLog(@"xxxx")
    self.msgText.text=NSHomeDirectory();
}
-(IBAction)docTap:(id)sender{
  NSArray * array=NSSearchForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);//搜索路径在当前Domains下,在那个路径下搜索,在当前用户目录搜索,路径是否展开
    NSLog(@"%@",[array objectAtIndex:0]);
   self.msgText.text=@"";
   self.msgText.text=[array objectAtIndex:0];//  d可能被当做转义
}
-(IBAction)libTap:(id)sender{
      NSArray * array=NSSearchForDirectoriesInDomains(NSLibraryirectory,NSUserDomainMask,YES);
   self.msgText.text=@"";
   self.msgText.text=[array objectAtIndex:0];
}
-(IBAction)tmpTap:(id)sender{
   self.msgText.text=NSTemporaryDirectory();
}

image-20220602173435707
image-20220602173547902


4、数据库网络之NSUserDefaults用户默认保存

如何在iOS中进行数据的保存,要将数据长久保存必须依靠文件,在iOS中要想使用文件,首先必须获得当前文件进行保存的路径,iOS中是一种沙盒机制一个应用程序磁盘对应自己自己空间这个空间不能被别人访问,即应用程序之间不能进行数据共享

创建单视图应用程序登录成功后密码保存

image-20220602175402752

//AppDelegate.m
@interface
@property (weak,nonatomic)IBOutlet UITextField * uname;
-(IBAction)loginTap:(id)sender;
-(IBAction)deleteTap:(id)sender;//删除默认事件
//ViewController.m
-(void)viewDidLoad{
    [super viewDidLoad];
    /*
    //是否已经正确登录过
    NSString * path=NSHomeDirectory();//当前应用程序根目录
    path=[path stringByAppendingPathCompoent:@"save.txt"];
    NSLog(@"path=%@",path);//刚开始没有这个文件,需要写过文件才会创建出这个文件
    NSString * uname=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    if(uname==nil){
        NSLog(@"还没保存过");
    }
    else{
        self.uname.text=uname;
    }
    */
    //第二种手段:采用用户默认保存方式  NSUserDefaults本质一个字典
    NSString * uname=[[NSUserDefaults standardUserDefaults]objectForKey:@"USERNAME"];
    if(uname==nil){
        NSLog(@"还没保存过");
    }
    else{
        self.uname.text=uname;
    }
}
-(IBAction)loginTap:(id)sender{
    NSString * str=self.uname.text;
    if(str.length>0){
        /*
         NSString * path=NSHomeDirectory();
         path=[path stringByAppendingPathCompoent:@"save.txt"];
         [str writeToFile:path atomically:YES];
         */
         [[NSUserDefaults standardUserDefaults]setObject:str forKey:@"USERNAME"];
    }
}
-(IBAction)deleteTap:(id)sender{
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"USERNAME"];
}

image-20220602180552435

54章

sqlite


安装数据库工具。Navicat for SQLite。

1、运行navicat for sqlite

2、新建一个连接(连接名,数据库的路径和它的文件名字)

3、保存信息每行记录,每列叫记录

image-20220602210555695

创建一个表:

image-20220602212145367


ddl  结构定义 create alter drop 
dml  数据操作 insert delete update select
create table t_cjb(xingming text not null,yuwen integer not null,shuxue integer not null,yingyu integer not null);
/*
real表示小数点
*/
create table if not exists feiyong(id integer,fy real);

-- 插入数据 只能插入一行
-- insert into 表名(字段列表)values(值的列表)
insert into t_student(name,telnum) values('11','22')
-- 修改数据
-- update 表名 set 字段名=值 .. where 条件
update t_student set telnum='138' where name='11'
-- 删除数据
-- delete from 表名 where 条件
delete from t_student where name='11'

-- 查询语句
-- select 字段列表 from 表名 where 条件 order by 字段名
select * from t_student -- *显示所有列
select name as 姓名 from t_student
select name 姓名 from t_student where name='张'
select * from t_student where name like '张%'
select count(*) from t_student where age<20
select * from t_student where age<20 and age>10 -- age<20 or age>10
select * from t_student where order by age --升序
select * from t_student where age<20 order by age desc --降序
select sum(yw) from t_student -- 统计函数
select avg(yw) from t_student 
select * ,yw+sx+yy as 总分 from t_student -- 计算

如何程序中使用数据库。创建单视图应用程序选择工程编译阶段选中链接库。

image-20220603100942749
image-20220603101106291
image-20220603101817998

-(IBAction)dbTap:(id)sender;
@property(weak,nonatomic)IBOutlet UITextField * nameText;
@property(weak,nonatomic)IBOutlet UITextField * ageText;
//ViewController.m
#import <sqlite3.h>
-(IBAction)dbTap:(id)sender{
    //操作数据库 1、打开数据库,2、操作数据库,3、关闭数据库
    //提供c的字符串,即我们打开数据库完整路径和文件名
    NSString * path=NSHomeDirectory();//获取沙盒路径
    path=[path stringAppendingPathComponent:@"mydb.sqlite"];//往路径增加文件名
    NSLog(@"%@",path);
    sqlite3 * db;//数据库指针
    //open如果没有这个数据库,并创建这个数据库文件并打开
    if(sqlite3_open([path UTF8String],&amp;db)!=SQLITE_OK){
        NSLog(@"打开失败");
    }
    //定制sql
    char * sql="create table if not exists t_student(name text,age integer)";
    char * err;//定制出错字符串
    if(sqlite3_exec(db,sql,NULL,NULL,&amp;err)!=SQLITE_OK){
        NSLog(@"sql运行失败:%s",err);
    }
    //增,删,改
    NSString * name=self.nameText.text;
    NSString * age=self.ageText.text;
    //sql="insert into t_student(name,age) values('张三',22)";
    /*NSString sql2=[NSString stringWithFormat:@"insert into t_student(name,age) values('%@',%@)",name,age];//动态sql,带'输入时候运行失败解决方法预处理绑定
    NSLog(@"%@",sql2);
    if(sqlite3_exec(db,[sql2 UIF8String],NULL,NULL,&amp;err)!=SQLITE_OK){
        NSLog(@"增加失败:%s",err);
    }
    */
    sql="insert into t_student(name,age) values(?,?)";
    sqlite3_stmt * stmt;
    if(sqlite23_prepare_v2(db,sql,-1,&amp;stmt,NULL)==SQLITE_OK){
        //绑定参数
        if(sqlite3_bind_text(stmt,1,[name UTF8String],-1,NULL)!=SQLITE_OK){
            NSLog(@"name绑定失败");
        }
        if(sqlite3_bind_int(stmt,2,[age intValue])!=SQLITE_OK){
            NSLog(@"age绑定失败");
        }
    }
    if(sqlite3_step(stmt)!=SQLITE_DONE){
        NSLog(@"插入失败");
    }
    
    /*
    sql="delete from t_student where name='123'";
    if(sqlite3_exec(db,sql,NULL,NULL,&amp;err)!=SQLITE_OK){
        NSLog(@"删除失败:%s",err);
    }*/
    sql="delete from t_student where name=?"
    if(sqlite3_prepare_v2(db,sql,-1,&amp;stmt,NULL)==SQLITE_OK){
        if(sqlite3_bind_text(stmt,1,[name UTF8String],-1,NULL)!=SQLITE_OK){
            NSLog(@"name绑定失败");
        }
    }
    if(sqlite3_step(stmt)!=SQLITE_DONE){
        NSLog(@"删除失败");
    }
    
    
    /*
    sql="update t_student set age=50 where name='李四'";
    if(sqlite3_exec(db,sql,NULL,NULL,&amp;err)!=SQLITE_OK){
        NSLog(@"修改失败:%s",err);
    }*/
    sql="update t_student set age=? where name=?"
    if(sqlite3_prepare_v2(db,sql,-1,&stmt,NULL)==SQLITE_OK){
        if(sqlite3_bind_int(stmt,1,[age intValue],-1,NULL)!=SQLITE_OK){
            NSLog(@"age绑定失败");
        }
        if(sqlite3_bind_text(stmt,2,[name UTF8String],-1,NULL)!=SQLITE_OK){
            NSLog(@"name绑定失败");
        }
    }
    if(sqlite3_step(stmt)!=SQLITE_DONE){
        NSLog(@"修改失败");
    }
    
    
    //查,查询之后如何得到表中数据
    sql="select * from t_student";
    //-1表示自己计算
    if(sqlite3_prepare_v2(db,sql,-1,&stmt,NULL)==SQLITE_Ok){
       //遍历返回结果
        while(sqlite3_step(stmt)==SQLITE_ROW){//得到一行
            char * name=(char *)sqlite3_column_text(stmt,0);//得到第几列
            int age=(int)sqlite3_column_int(stmt,1);
            NSString * strName=[NSString stringWithUTF8String:@"%s",name];
            NSLog(@"name=%@,age=%d",strName,age);
        }
    }
    else{
        NSLog(@"预处理失败");
    }
    
    
    sqlite3_finalize(stmt);//释放资源
    sqlite3_close(db);
}

image-20220603103057445
image-20220603110659277

55章

Core Data

iOS原带的Core Data数据库使用详解


Core Data持久工具能将对象直接存储数据库中。创建单视图应用程序勾选持久框架

image-20220603171635253

APPDelegate.h

image-20220603172000071

//AppDelegate.m
-(BOOL)appliaction:(UIAppliaction *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    NSLog(@"%@",NSHomeDirectory());//根路径
    NSLog(@"%@",[self applicationDocumentsDirectory]);//文档路径
    return YES;
}

表名首字母需要大写

image-20220603173130390

@interface
@property(weak,nonatomic)IBOutlet UITextField * name;
@property(weak,nonatomic)IBOutlet UITextField * age;
-(IBAction)add:(UIButton *)sender;
-(IBAction)find:(UIButton *)sender;//查询
-(IBAction)delete:(UIButton *)sender;
-(IBAction)update:(UIButton *)sender;
//ViewController.m
#import "AppDelegate.h"
-(void)viewDidLoad{
   [super viewDidLoad];
   /*
   AppDelegate * app=[UIApplication shareApplication].delegate; //获得应用程序代理
   NSManagedObjectContext * context=app.manageObjectContext;//获得托管上下文对象自动创建数据库。
   //定义一个托管对象上下文就是数据库实体就是表
   */
}
-(IBAction)add:(UIButton *)sender{
   NSString * name=self.name.text;
   NSString * age=self.age.text;
   name=[name stringByTrimmingCharactersInset:[NScharacterSet WhitespaceCharacterSet]];
   age=[age stringByTrimmingCharactersInset:[NScharacterSet WhitespaceCharacterSet]];
   if([name isEqualToString:@""]){
       UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"姓名不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:,nil];
       return;
   }
   if([age isEqualToString:@""]){
       UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"年龄不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:,nil];
   }
   
   
   AppDelegate * app=[UIApplication shareApplication].delegate; 
   NSManagedObjectContext * context=app.manageObjectContext;
   //定义一个托管对象
   NSManageObject * mo=[NSEntityDescription insertNewObjectForEntityForName:@"Student" inManageObjectContext:context];
   [mo setValue:name forKey:@"name"];
   NSNumber * num=[NSNumber numberWithInt:age.intValue];
   [mo setValue:num forKey:@"age"];
   [context insertObject:mo];
   NSError * error;
   if(![context save:&error]){
       NSLog(@"error=%@",[error description]);
   }
   else{
       NSLog(@"插入成功!");
   }
}

-(IBAction)find:(UIButton *)sender{
   AppDelegate * app=[UIApplication shareApplication].delegate; 
   NSManagedObjectContext * context=app.manageObjectContext;
   //实体指的就是表
   NSEnttityDescriptiotn * entity=[NSEntityDescription entityForName:@"Student" inManageObjectContext:context];
   //NSFetchRequest * request=[NSFetchRequest fetchRequestWithEntityName:entity];
   NSFetchRequest * request=[[NSFetchRequest alloc]init];
   [request setEntity:entity];
   
   //谓词
   NSString * pred=[NSpredicate predicateWIthFormat:@"(age=%d)",22];
   [request setPredicate:pred];
   
   NSError * error=nil;
   NSArray * objects=[context executeFetchRequest:request error:&error];
   if(objects){//查询成功
       NSLog(@"%ld",objects.count);
       for(NSManagedObejct * mo in objects){//每个学生信息
           NSLog(@"name=%@,age=%@",[mo valueForKey:@"name"],[mo valueForKey:@"age"]);
       }
   }
}

-(IBAction)delete:(UIButton *)sender{
   AppDelegate * app=[UIApplication shareApplication].delegate; 
   NSManagedObjectContext * context=app.manageObjectContext;
   NSEnttityDescriptiotn * entity=[NSEntityDescription entityForName:@"Student" inManageObjectContext:context];
   NSFetchRequest * request=[[NSFetchRequest alloc]init];
   [request setEntity:entity];
   NSString * pred=[NSpredicate predicateWIthFormat:@"(age=%d)",22];
   [request setPredicate:pred];
   
   NSError * error=nil;
   NSArray * objects=[context executeFetchRequest:request error:&error];
   if(objects){//查询成功
       NSLog(@"%ld",objects.count);
       for(NSManagedObejct * mo in objects){//mo就是一个托管对象
           [mo deleteObject:mo];
       }
   }
   [context save:nil];//真正删除
}

-(IBAction)update:(UIButton *)sender{
   AppDelegate * app=[UIApplication shareApplication].delegate; 
   NSManagedObjectContext * context=app.manageObjectContext;
   NSEnttityDescriptiotn * entity=[NSEntityDescription entityForName:@"Student" inManageObjectContext:context];
   NSFetchRequest * request=[[NSFetchRequest alloc]init];
   [request setEntity:entity];
   NSString * pred=[NSpredicate predicateWIthFormat:@"(age=%d)",22];
   [request setPredicate:pred];
   
   NSError * error=nil;
   NSArray * objects=[context executeFetchRequest:request error:&error];
   if(objects){//查询成功
       NSLog(@"%ld",objects.count);
       for(NSManagedObejct * mo in objects){//mo就是一个托管对象
           [mo setValue:[NSNumber numberWithInt:44] forKey:@"age"];//修改年龄
       }
   }
   [context save:nil];
}

image-20220603173831843
image-20220603174029368

企业中使用CoreData框架技术的只是少部分。但这并没有使用第三方组件来的更快一些。更多使用fastq技术

56章

登录注册

数据库应用网络登录和注册。创建单视图应用程序

image-20220604105308194

点击return关闭键盘

image-20220604111440553

点击视图关闭键盘

image-20220604111742362
image-20220604111842722


@interface ViewController :UIViewController
{
    BOOL isRember;
}
//创建输出口和动作
@property (weak,nonatomic)IBOutlet UITextFeld * unameText;
@property (weak,nonatomic)IBOutlet UITextFeld * upassText;
@property (weak,nonatomic)IBOutlet UIButton * remButton;
-(IBAction)remTap:(UIButton *)sender;
@property (weak,nonatomic)IBOutlet UIButton * loginButton;//点击登录之后变灰
-(IBAction)loginTap:(UIButton *)sender;
@property (weak,nonatomic)IBOutlet UIButton * registButton;
-(IBAction)registTap:(UIButton *)sender;

-(IBAction)closeKeyboar:(UITextField *)sender;//两个文本框的关闭键盘动作都指向这个
-(IBAction)closeKB:(id)sender;

//ViewController.m
#import <sqlite3.h>
#import "MFUtil.h"
#import "MFDatabase.h"
-(void)viewDidLoad{
    [super viewDidLoad];
    isRember=NO;
    
    if(![MFDatabase openDatabase:@"user.sqlite"]||![MFDatabase execSql:@"create table if not exists t_user(uname text not null,upass text not null)"]){
        self.view.userInteractionEnabled=NO;
    }
 
    NSString * uname=[[NSUserDefaults standardUserDefaults]objectForKey:@"USERNAME"];
    NSString * upass=[[NSUserDefaults standardUserDefaults]objectForKey:@"USERPASS"];
    if(uname.length>0&&upass.length>0){
        isRember=YES;
        [self.remButon setBackgroundImage:[UIImage imageNamed:@"check.png"]forState:UIControlStateNormal];
        self.unameText.text=uname;
        self.upassText.text=upass;
    }
        
}

-(IBAction)remTap:(UIButton *)sender{
    if(isRember==NO){//点击切换状态
      [sender setBackgroundImage:[UIImage imageNamed:@"check.png"]forState:UIControlStateNormal];
      isRember=YES;
    }
    else{
      [sender setBackgroundImage:[UIImage imageNamed:@"nocheck.png"]forState:UIControlStateNormal];
      isRember=NO;
    }
}

-(void)lockView:(BOOL *)_lock andShowTitle:(NSString *)_str andSender:(UIButton *)_sender{
    [self closeKB:nil];
    [_sender setTitle:_str forState:UIControlStateNormal];
    self.view.userInteractionEnabled=_lock;//封锁或者解锁
}
-(IBAction)loginTap:(UIButton *)sender{
     NSString * uname=self.unameText.text;
     NSString * upass=self.upassText.text;
     uname=[MFUitil trim:uname];
     upass=[MFUitil trim:upass];
     NSLog(@"name=%@,pass=%@",uname,upass);
     if([uname isEqualToString@""]){
        /*
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"账号不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        */
        [MFUtil alert:@"账号不能为空"];
        self.unameText.text=@"";
        [self.unameText becomeFirstResponder];
        return;
    }
    if([upass isEqualToString@""]){
        /*
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"密码不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];*/
        [MFUtil alert:@"密码不能为空"];
        self.upassText.text=@"";
        [self.upassText becomeFirstResponder];
        return;
    }
    /*
    [self closeKB:nil];
    [self.loginButton setTitle:@"正在登录..." forState:UIControlStateNormal];
    self.view.userInteractionEnabled=NO;*/
    [self lockView:NO andShowTitle:@"正在登录..." andSender:self.loginButton];
    
    /*char * path=NSHomeDirectory();
    path=[path stringByAppendingPathComponetn:@"user.sqlite"];
    NSLog(@"path=%@",path);
    sqlite3 * db;
    int result=sqlite3_open([path UTF8String],&db);
    if(result!=SQLITE_OK){
        NSLog(@"数据库打开失败....");
        sqlite3_close(db);
        return;
    }*/
    
    
    //检查用户是否存在,查询sql
    
    char *  sql="select * from t_user where uname=? and upass=?";
    sqlite3_stmt * stmt;
    result=sqlite3_prapare_v2(db,sql,-1,&stmt,NULL);
    
    if(result!=SQLITE_OK){
        NSLog(@"陈述绑定失败");
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return;
    }
    
    if(sqlite3_bind_text(stmt,1,[uname UTF8String],-1,NULL)!=SQLITE_OK){
        NSLog(@"uname绑定失败");
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return;
    }
    if(sqlite3_bind_text(stmt,2,[upass UTF8String],-1,NULL)!=SQLITE_OK){
        NSLog(@"upass绑定失败");
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return;
    }
    
    if(sqlite3_step(stmt)==SQLITE_ROW){//如果有用户信息
        /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"登录成功" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];*/
        [MFUtil alert:@"登录成功"];
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        /*
        self.view.userInteractionEnabled=YES;
        [self.loginButton setTitlte:@"登录" forState:UIControlStateNormal];*/
        [self lockView:YES andShowTitle:@"登录" andSender:self.loginButton];
        
        //进入程序主界面
        if(isRember){
           [[NSUserDefaults stanardUserDefaults] setObject:uname forKey:@"USERNAME"];
           [[NSUserDefaults stanardUserDefaults] setObject:upass forKey:@"USERPASS"];
        }
        else{
           [[NSUserDefaults stanardUserDefaults] removeObject:uname forKey:@"USERNAME"];
           [[NSUserDefaults stanardUserDefaults] removeObject:upass forKey:@"USERPASS"];
        }
        
        return;
    }
    
     /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"登录失败" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
     [alert show];*/
    [MFUtil alert:@"登录失败"];
    sqlite3_finalize(stmt);
    sqlite3_close(db);
    /*
    self.view.userInteractionEnabled=YES;
    [self.loginButton setTitlte:@"登录" forState:UIControlStateNormal];*/
    [self lockView:YES andShowTitle:@"登录" andSender:self.loginButton];
}
-(IBAction)registTap:(UIButton *)sender{
    NSString * uname=self.unameText.text;
    NSString * upass=self.upassText.text;
    //数据有效性验证
    //剔除前后空格
    uname=[MFUitil trim:uname];
    upass=[MFUitil trim:upass];
    NSLog(@"name=%@,pass=%@",uname,upass);
    if([uname isEqualToString@""]){
        /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"账号不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];*/
        [MFUtil alert:@"账号不能为空"];
        self.unameText.text=@"";
        [self.unameText becomeFirstResponder];//重新获得焦点
        return;
    }
    if([upass isEqualToString@""]){
        /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"密码不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];*/
        [MFUtil alert:@"密码不能为空"];
        self.upassText.text=@"";
        [self.upassText becomeFirstResponder];
        return;
    }
    
    /*
    [self closeKB:nil];
    [self.registButton setTitle:@"正在注册..." forState:UIControlStateNormal];
    //self.registButton.enabled=NO;//封锁注册按钮,避免重复注册,按道理应该封锁整个界面
    self.view.userInteractionEnabled=NO;//不允许视图与用户进行交互 */
    [self lockView:NO andShowTitle:@"正在注册..." andSender:self.registButton];
    
    //检查用户是否存在链接数据库
    //Build 增加数据库文件,选择动态链接库libsqlite3.dylib导入头文件
    /*
    char * path=NSHomeDirectory();
    path=[path stringByAppendingPathComponetn:@"user.sqlite"];
    NSLog(@"path=%@",path);
    sqlite3 * db;
    int result=sqlite3_open([path UTF8String],&db);//打开数据库
    if(result!=SQLITE_OK){
        NSLog(@"数据库打开失败....");
        sqlite3_close(db);
        return;
    }
    

    char * sql="create table if not exists t_user(uname text not null,upass text not null)";//创建用户表
    char * error;
    restult=sqlite3_exec(db,sql,NULL,NULL,&error);//运行sql
    if(result!=SQLITE_OK){
        NSLog(@"创建用户表失败....,error=%@",error);
        sqlite3_close(db);
        return;
    }*/
    
    //检查用户是否存在,查询sql
    char * sql="select * from t_user where uname=?";
    sqlite3_stmt * stmt;
    int result=sqlite3_prapare_v2([MFDatabase getDb],sql,-1,&stmt,NULL);
    
    if(result!=SQLITE_OK){
        NSLog(@"陈述绑定失败");
        sqlite3_finalize(stmt);
        //sqlite3_close(db);
        return;
    }
    
    if(sqlite3_bind_text(stmt,1,[uname UTF8String],-1,NULL)!=SQLITE_OK){
        NSLog(@"uname绑定失败");
        sqlite3_finalize(stmt);
        //sqlite3_close(db);
        return;
    }
    
    if(sqlite3_step(stmt)==SQLITE_ROW){
        /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"用户名已存在" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];*/
        [MFUtil alert:@"用户名已存在"];
        sqlite3_finalize(stmt);
        //sqlite3_close(db);
        /*
        self.view.userInteractionEnabled=YES;//视图解锁
        [self.registButton setTitlte:@"注册" forState:UIControlStateNormal];*/
        [self lockView:YES andShowTitle:@"注册" andSender:self.registButton];
        return;
    }
    
    //增加用户sql
    sql="inset into t_user valuse(?,?)";
    sqlite3_finalize(stmt);//先释放前面查询的陈述
    result=sqlite3_prapare_v2(db,sql,-1,&stmt,NULL);
    
    if(result!=SQLITE_OK){
        NSLog(@"陈述绑定失败");
        sqlite3_finalize(stmt);
        //sqlite3_close(db);
        return;
    }
    
    if(sqlite3_bind_text(stmt,1,[uname UTF8String],-1,NULL)!=SQLITE_OK){
        NSLog(@"uname绑定失败");
        sqlite3_finalize(stmt);
        //sqlite3_close(db);
        return;
    }
    if(sqlite3_bind_text(stmt,2,[upass UTF8String],-1,NULL)!=SQLITE_OK){
        NSLog(@"upass绑定失败");
        sqlite3_finalize(stmt);
        //sqlite3_close(db);
        return;
    }
    
    if(sqlite3_step(stmt)!=SQLITE_DONE){//预处理失败
        /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"注册失败" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];*/
        [MFUtil alert:@"注册失败"];
        sqlite3_finalize(stmt); 
        //sqlite3_close(db);
        return;
    }
    
    /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"注册成功" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
    [alert show];*/
    [MFUtil alert:@"注册成功"];
    sqlite3_finalize(stmt); 
    //sqlite3_close(db);
    /*
    self.view.userInteractionEnabled=YES;//解锁视图
    [self.registButton setTitlte:@"注册" forState:UIControlStateNormal];*/
    [self lockView:YES andShowTitle:@"注册" andSender:self.registButton];
}

-(IBAction)closeKeyboar:(UITextField *)sender{
}

-(IBAction)closeKB:(id)sender{
    //让两个文本框失去焦点
    [self.unameText resignFirstResponder];//resign重新设置
    [self.upassText resignFirstResponder];
}

@interface
+(void)alert:(NSString *)msg;
+(NSString *)trim:(NSString *)_str;
//MFUtil.m
#import <UIKit/UIKit.h>
+(void)alert:(NSString *)msg{
      UIAlertView * av=[[UIAlertView alloc]initWithTitle:@"友情提示"message:msg delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
      [av show];
}
+(NSString *)trim:(NSString *)_str{
    return [_str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
#import "sqlite3.h"
@interface
+(BOOL)openDatabase:(NSString *)_name;
+(BOOL)execSql:(NSString *)_sql;
+(sqlite3 *)getDb;
//MFDatabase.m
#import "MFUtil.h"
static sqlite3 * db=NULL;
+(BOOL)openDatabase:(NSString *)_name{
    NSString * path=NSHomeDirectory();
    path=[path stringByAppendingPathComponent:_name];
    NSLog(@"path=%@",path);
    int result=sqlite3_open([path UTF8String],&db);
    if(result!=SQLITE_OK){
        NSLog(@"数据库打开失败....");
        sqlite3_close(db);
        return NO;
    }
    return YES;
}
+(BOOL)execSql:(NSString *)_sql{
    char * error;
    int restult=sqlite3_exec(db,[_sql UTF8String],NULL,NULL,&error);//运行sql
    if(result!=SQLITE_OK){
        NSLog(@"%@运行失败,error=%@",_sql,error);
        //sqlite3_close(db);
        return;
    }
    return YES;
}
+(sqlite3 *)getDb{
    return db;
}

57章

web

iOS数据库网络之Web介绍mac系统自带Apache服务器

# 启动localhost服务
sudo apachectl start
# /资源库/WebServer/Documents/index.html.en 
# 网页文件:静态htm html  动态asp aspx jsp php

html

<!-- index.html -->
<html>
    <head>
         <!-- 指定字符集否则汉字乱码 -->
         <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
		<title>hello</title>
    </head>
    <body>
<!-- 文字图片超级链接表格多媒体表单对象,javascript -->
        &nbsp
        <br>
        <!-- 建议使用单引号 -->
        <front size='8' color='red'></front>
        <img src='logo.png' width='100' heigth='200'>
        <a href='b.html'>跳转</a>
        <table border='1' align='center'>
            <tr>
                <td>111</td>
                <td>222</td>
                <td>333</td>
            </tr>
            <tr>
                <td>111</td>
                <td>222</td>
                <td>333</td>
            </tr>
        </table>
        <input type='text'><input type='button' value='确定' onclick='ontap();'>
        <input type='radio'><input type='checkbox'>
        
        <center>居中显示</center>
        <hr>
        <form action="login.php" method="post">
        <table align='center' border='1' width='300'>
            <tr>
                <td>账号</td>
                <td><input type='text' maxlength='10' name="uname"></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type='password' maxlength='10' name="upass"></td>
            </tr>
            <tr>
                <td><input type='submit' value='登录' name="action"></td>
                <td><input type='submit' value='注册' name="action"></td>
            </tr>
        </table>        
        </form>
        
    </body>
</html>
<script>
    function ontap(){
        alert("hello");
    }
</script>
//login.php
<html>
    <head>
    	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
   		<title></title>
    </head>
    <body>
    	<?
    	 	echo 12*12;//输出语句
		    echo "你好";
			$a=123;//定义变量
			echo $a;
			if($a>0) echo "正数";
             else echo "负数";
			for($b=1;$b<4;$b++) echo $b;
    	?>
         <script>
             document.write("hello");
         </script>
    </body>
</html>

image-20220605200229191

开启浏览器解析php文件。/ect/apache2/httpd.conf/。

image-20220605200426498

终端重启apacheweb服务sudo apachectl stop

image-20220605201242423

php区别前面静态页面动态页面里面代码服务器端运行


mysql

iOS可以嵌入sqlite3,但是web端是不能运用的,web应该使用mysql安装mysql数据库。安装mysql服务

image-20220605202546165

启动mysql服务

image-20220605202631981

安装地址:/usr/local/mysql/。安装数据库管理工具

image-20220605202815008

打开管理工具链接数据库。修改密码:

update `user` set Password=PASSWORD("1234") where User="root"
<html>
    <head>
    	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
   		<title></title>
    </head>
    <body>
//db.phpphp操作数据库 1、链接和MySql和数据库,2、对数据库进行操作,3、关闭数据库
        <?
        echo "hello!";
        $conn=mysql_connetc("127.0.0.1","root","1234");
        if(!$conn) die("链接失败!!!");//相当return
        //指定数据库
        $result=mysql_select_db("zhq",$conn);
        if(!$result) {
            mysql_close(conn);
            die("指定失败!!!");
        }
	   $sql="insert into t_user(uname,upass) values('111','2222')";
	   $result=mysql_query($sql);
        if(!$result) {
            mysql_close(conn);
            die("插入失败!");
        }

	   $sql="update t_user set upass='2334' where uname='111'";
	   $result=mysql_query($sql);
        if(!$result) {
            mysql_close(conn);
            die("修改失败!");
        }

	   $sql="delete from t_user where uname='111'";
	   $result=mysql_query($sql);
        if(!$result) {
            mysql_close(conn);
            die("删除失败!");
        }
        

	   //查询
	   $sql="select * from t_user";
	   $rs=mysql_query($sql);//结果保存到变量rs中
        if(!$rs) {
            mysql_close(conn);
            die("查询失败!");
        }
	   $recordcount=mysql_num_row($rs);//得到返回行数
	   echo $recordcount;
	   if($recordcount>0){//如果有返回
           echo "<table border='1' align='center'>";
           echo "<tr>";
           echo "<td>";
           echo "用户名";
           echo "</td>";
           echo "<td>";
           echo "密码";
           echo "</td>";
           echo "</tr>";
           while($row=mysql_fetch_assoc($rs)){//得到行,遍历每一行
               $uname=$row['uname'];
               $upass=$row['upass'];
               echo "<tr>";
               echo "<td>";
                   echo $uname;
               echo "</td>";
               echo "<td>";
                   echo $upass;
               echo "</td>";
               echo "</tr>";
           }
           echo "</table>";
       }

        mysql_close(conn);

        ?>
    </body>
</html>

php

数据库网络之php的登录和注册。

<html>
    <head>
    	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
   		<title></title>
    </head>
    <body>
        <?
		//得到index.html提交的用户名和密码
    	//$uname=$_GET['uname'];
	    //$upass=$_GET['upass'];
		$uname=$_POST['uname'];
		$upass=$_POST['upass'];
		//数据有效性验证
		$uname=trim($uname);
		$upass=trim($upass);
		if($uname==""||$upass==""){
            //直接导航回到index.html
            echo "<script>loaction.href='index.html';</script>";
        }
		$action=$_POST['action'];
		$conn=mysql_connect("127.0.0.1","root","1234");
		if(!$conn) die("链接失败!");
	    $result=mysql_select_db("zhq",conn);
         if(!$result) {
             mysql_close($conn);
             die("指定失败!");
         }
		if($action=="登录"){
           // echo "dl!";
            $sql="select * from t_user where uname=' " .$uname. " and upass=' " .$upass. " ";
            //echo $sql;
            $rs=mysql_query($sql);
            if(!$rs){
                mysql_close($conn);
                die("查询失败!");
            }
            $recordCount=mysql_num_row($rs);
            if($recordCount>0){
                echo "登录成功!!!";
            }
            else{
                else echo "账号或密码!!!点击返回<a href='index.html'>登录</a>";
            }
            
        }
	    else if($action=="注册"){
            //查看用户名是否存在
            $sql="select * from t_user where uname=' " .$uname. " ";
            echo $sql;
            $rs=mysql_query($sql);
            if(!$rs){
                mysql_close($conn);
                die("查询失败!");
            }
            $recordCount=mysql_num_row($rs);
            //echo $recordCount;
            if($recordCount>0){
                mysql_close($conn);
                die("用户已经存在!!!点击返回<a href='index.html'>注册</a>");
            }
            else{
                $sql="insert into t_user(uname,upass) values(' ".$uname." ',' ".$upass." ')";
                $rs=mysql_query($sql);
                if(!$rs){
                    mysql_close($conn);
                    die("注册失败!");
                }
                else echo "注册成功!!!点击返回<a href='index.html'>登录</a>";
            }
        }
	    else echo "erro!";//不是从index.html过来的
		mysql_close($conn);
	    //echo $uname;
	    //echo $upass;

        ?>
    </body>
</html>

58章

登录注册

iOS基于网络的客户端登录和注册。

界面搭建,数据验证web交互,网络请求,GET提交,POST提交


创建单视图应用程序。移动端网络版的登录和注册。Portrait水平。

image-20220606082140699

image-20220606094209121

@interface ViewController:UIViewController<NSURLConnectionDataDelegate>
{
    NSMutableData * receiveData;
    BOOL action;//yes代表注册,no代表登录
}
@property (weak,nonatomic)IBOutlet UITextField * userText;
@property (weak,nonatomic)IBOutlet UITextField * passwordText;
-(IBAction)loginTap:(UIButton *)sender;
-(IBAction)registTap:(UIButton *)sender;

-(IBAction)asyLoginTap(UIButton *)sender;
-(IBAction)asyRegistTap:(UIButton *)seder;

-(IBAction)closKey:(id)sender;

//ViewController.m

-(IBAction)closKey:(id)sender{}
    
-(IBAction)asyLoginTap(UIButton *)sender{
    action=NO;
    NSString * uname=self.userText.text;
    NSString * upass=self.passwordText.text;
    uname=[uname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    upass=[upass stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if([uname isEuqalToString:@""]){
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"账号不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        self.userText.text=@"";
        [self.userText becomeFirstResponder];
        return;
    }
    if([uname isEuqalToString:@""]){
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"密码不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        self.userText.text=@"";
        [self.userText becomeFirstResponder];//重新获得焦点
        return;
    }
    //通过网络注册,url字符构建
    NSString * path=[NSString stringWithFormat@"http://192.168.1.52/php/login_regist.php?action=login&uname=%@&upass=%@",uname,upass];
    NSlog(@"path=%@",path);
    NSURL * url=[NSURL URLWithString:path];
    NSURLRequest * request=[NSURLRequset requestWithURL:url];
    //异步请求
    NSURLConnection * conn=[NSURLConnection connectionWithRequest:request delegate:self];

    if(conn==nil){//断网
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"服务器链接失败" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
    }
    else{
        receiveDat=[[NSMuatbleData alloc]init];
    }        
}
//有响应的,有数据要返回
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"返回开始!");
    [receiveData setLength:0];//清除数据
}
//接收数据,可能产生多次
-(vid)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
     NSLog(@"不断接收数据!");
    [receiveData appendData:data];
}
//数据接收完成
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
     NSLog(@"接收完成!");
     NSString * str=[[NSString alloc]initWithData:receiveData encoding:NSUIT8StringEncoding];
    NSLog(@"%@",str);
    if(!action){
        NSRange range=[str rangeOfString:@"sucess"];
        if(range.location!=NSNotFound){
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"登录成功!" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
            [alert show];
            return;
        } 
        else{
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"登录失败!" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
            [alert show];
        }
    }
    else{
        
        NSRange range=[str rangeOfString:@"sucess"];
        if(range.location!=NSNotFound){
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"注册成功!" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
            [alert show];
            return;
        }
        range=[str rangeOfString:@"exist"];
        if(range.location!=NSNotFound){
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"用户已存在!" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
            [alert show];
            return;
        }
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"注册失败!" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        
    }
}
//发生错误时候
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
     NSLog(@"产生错误!");
     UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"服务器链接失败" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
     [alert show];
}
    

-(IBAction)asyRegistTap:(UIButton *)seder{
    action=YES;
    NSString * uname=self.userText.text;
    NSString * upass=self.passwordText.text;
    uname=[uname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    upass=[upass stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if([uname isEuqalToString:@""]){
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"账号不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        self.userText.text=@"";
        [self.userText becomeFirstResponder];
        return;
    }
    if([uname isEuqalToString:@""]){
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"密码不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        self.userText.text=@"";
        [self.userText becomeFirstResponder];//重新获得焦点
        return;
    }
    //通过网络注册,url字符串构建
    NSString * path=[NSString stringWithFormat@"http://192.168.1.52/php/login_regist.php?action=regist&uname=%@&upass=%@",uname,upass];
    NSlog(@"path=%@",path);
    NSURL * url=[NSURL URLWithString:path];
    NSURLRequest * request=[NSURLRequset requestWithURL:url];
    //异步请求
    NSURLConnection * conn=[NSURLConnection connectionWithRequest:request delegate:self];

    if(conn==nil){//断网
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"服务器链接失败" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
    }
    else{
        receiveDat=[[NSMuatbleData alloc]init];
    }  
    
}



-(IBAction)loginTap:(UIButton *)sender{
    NSString * uname=self.userText.text;
    NSString * upass=self.passwordText.text;
    uname=[uname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    upass=[upass stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if([uname isEuqalToString:@""]){
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"账号不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        self.userText.text=@"";
        [self.userText becomeFirstResponder];
        return;
    }
    if([uname isEuqalToString:@""]){
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"密码不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        self.userText.text=@"";
        [self.userText becomeFirstResponder];//重新获得焦点
        return;
    }
    //通过网络注册,url字符串构建
    NSString * path=[NSString stringWithFormat@"http://192.168.1.52/php/login_regist.php?action=login&uname=%@&upass=%@",uname,upass];
    NSlog(@"path=%@",path);
    NSURL * url=[NSURL URLWithString:path];
    NSURLRequest * request=[NSURLRequset requestWithURL:url];
    //同步请求,按顺序等待请求(不合理)
    NSData * data=[NSURLConnection sendAynchronousRequest:request returningResponse:nil error:nil];
    
    if(data==nil){//断网的时候
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"服务器链接失败" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
    }
    else{
        NSString * str=[[NSString alloc]]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        
        
        NSRange range=[str rangeOfString:@"sucess"];
        if(range.location!=NSNotFound){
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"登录成功!" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
            [alert show];
            return;
        }        
        
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"失败!" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        
}

    
    
-(IBAction)registTap:(UIButton *)sender{
    NSString * uname=self.userText.text;
    NSString * upass=self.passwordText.text;
    //去除空格
    uname=[uname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    upass=[upass stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    //有效性检查
    if([uname isEuqalToString:@""]){
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"账号不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        self.userText.text=@"";
        [self.userText becomeFirstResponder];//重新获得焦点
        return;
    }
    if([uname isEuqalToString:@""]){
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"密码不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        self.userText.text=@"";
        [self.userText becomeFirstResponder];//重新获得焦点
        return;
    }
    //通过网络注册,url字符串构建
    NSString * path=[NSString stringWithFormat@"http://192.168.1.52/php/login_regist.php?action=regist&uname=%@&upass=%@",uname,upass];
    NSlog(@"path=%@",path);
    NSURL * url=[NSURL URLWithString:path];
    NSURLRequest * request=[NSURLRequset requestWithURL:url];
    NSData * data=[NSURLConnection sendAynchronousRequest:request returningResponse:nil error:nil];
    
    if(data==nil){//断网的时候
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"服务器链接失败" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
    }
    else{
        NSString * str=[[NSString alloc]]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        
        
        NSRange range=[str rangeOfString:@"sucess"];
        if(range.location!=NSNotFound){
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"注册成功!" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
            [alert show];
            return;
        }
        range=[str rangeOfString:@"exist"];
        if(range.location!=NSNotFound){
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"用户已存在!" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
            [alert show];
            return;
        }
        
        
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"失败!" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        
    }
}
<!-- index.html -->
<html>
    <head>
         <!-- 指定字符集否则汉字乱码 -->
         <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
		<title>hello</title>
    </head>
    <body>
        <form action="regist.php" method="post">
        <table align='center' border='1' width='300'>
            <tr>
                <td>账号</td>
                <td><input type='text' maxlength='10' name="uname"></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type='password' maxlength='10' name="upass"></td>
            </tr>
            <tr>
                <!--<td><input type='hidden' value='登录' name="action"></td>-->
                <td colspan="2"><input type='submit' value='注册' name="action"></td>
            </tr>
        </table>        
        </form>
        
    </body>
</html>
//login_regist.php
<?
//$uname=$_GET['uname'];
//$upass=$_GET['upass'];
$uname=$_POST['uname'];
$upass=$_POST['upass'];
if($uname==""||$upass==""){
    //直接导航回到index.html
    echo "<script>loaction.href='index.html';</script>";
}
$action=$_POST['action'];
$conn=mysql_connect("127.0.0.1","root","1234");
if(!$conn) die("error");
$result=mysql_select_db("zhq",conn);
if(!$result) {
    mysql_close($conn);
    die("error");
}
//设定字符集防止中文乱码
$sql="set names utf8";
if($action=="login"){
    $sql="select * from t_user where uname=' " .$uname. " and upass=' " .$upass. " ";
    $rs=mysql_query($sql);
    if(!$rs){
        mysql_close($conn);
        die("error");
    }
    $recordCount=mysql_num_row($rs);
    if($recordCount>0){
        echo "sucess";
    }
    else{
        else echo "error";
    }

}
else if($action=="regist"){
    //查看用户名是否存在
    $sql="select * from t_user where uname=' " .$uname. " ";
    echo $sql;
    $rs=mysql_query($sql);
    if(!$rs){
        mysql_close($conn);
        die("error");
    }
    $recordCount=mysql_num_row($rs);
    //echo $recordCount;
    if($recordCount>0){
        mysql_close($conn);
        die("exist");
    }
    else{
        $sql="insert into t_user(uname,upass) values(' ".$uname." ',' ".$upass." ')";
        $rs=mysql_query($sql);
        if(!$rs){
            mysql_close($conn);
            die("error");
        }
        else echo "success";
    }
}
else echo "erro";
mysql_close($conn);
?>
            
/*
//regist.php
<?
    $uname=$_GET['uname'];
$upass=$_GET['upass'];
if($uname==""||$upass==""){
    echo "<script>loaction.href='index.html';</script>";
}
$conn=mysql_connect("127.0.0.1","root","1234");
if(!$conn) die("error!");
$result=mysql_select_db("zhq",conn);
if(!$result) {
    mysql_close($conn);
    die("error!");
}
$sql="select * from t_user where uname=' " .$uname. " ";
echo $sql;
$rs=mysql_query($sql);
if(!$rs){
    mysql_close($conn);
    die("error!");
}
$recordCount=mysql_num_row($rs);
if($recordCount>0){
    mysql_close($conn);
    die("exist");
}
else{
    $sql="insert into t_user(uname,upass) values(' ".$uname." ',' ".$upass." ')";
    $rs=mysql_query($sql);
    if(!$rs){
        mysql_close($conn);
        die("error");
    }
    else echo "success";
}
mysql_close($conn);
?>
*/

POST提交数据

@interface ViewController:UIViewController
@property (weak,nonatomic)IBOutlet UITextField * userText;
@property (weak,nonatomic)IBOutlet UITextField * passwordText;

-(IBAction)queryTap:(UIButton *)sender;
-(IBAction)closKey:(id)sender;
-(IBAction)updateTap:(UIButton *)sender;

//ViewController.m

-(IBAction)closKey:(id)sender{}
-(IBAction)updateTap:(UIButton *)sender{
    NSString * uname=self.userText.text;
    NSString * upass=self.passwordText.text;
    //去除空格
    uname=[uname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    upass=[upass stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    //有效性检查
    if([uname isEuqalToString:@""]){
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"账号不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        self.userText.text=@"";
        [self.userText becomeFirstResponder];//重新获得焦点
        return;
    }
    if([uname isEuqalToString:@""]){
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"密码不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        self.userText.text=@"";
        [self.userText becomeFirstResponder];//重新获得焦点
        return;
    }
    
    //通过网络注册,url字符串构建
    NSString * path=[NSString stringWithFormat@"http://192.168.1.52/php/update.php"];
    NSlog(@"path=%@",path);
    NSURL * url=[NSURL URLWithString:path];
    NSMutableURLRequest * request=[[NSMutableURLRequest alloc]requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];//创建友缓存机制的请求
    [request setHTTPMethod:@"post"];
    NSString * strPar=@"uname=1&upass=1222";//参数字符串
    NSData * data=[strPar dataUsingEncoding:NSUTF8StringEncodig];//二进制数字符串
    [request setHTTPBody:data];//放到请求里
    NSData * revData=[NSURLConnection sendAynchronousRequest:request returningResponse:nil error:nil];
    
    if(revData==nil){//断网的时候
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"服务器链接失败" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
    }
    else{
        NSString * str=[[NSString alloc]]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        
        
        
        /*
        
        NSRange range=[str rangeOfString:@"sucess"];
        if(range.location!=NSNotFound){
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"注册成功!" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
            [alert show];
            return;
        }
        range=[str rangeOfString:@"exist"];
        if(range.location!=NSNotFound){
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"用户已存在!" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
            [alert show];
            return;
        }
        
        
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"失败!" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        
        */
    }
}
-(IBAction)updateTap:(UIButton *)sender{
    
}
//update.php
<?
$uname=$_POST['uname'];
$upass=$_POST['upass'];
if($uname==""||$upass==""){
    echo "<script>loaction.href='index.html';</script>";
}
$conn=mysql_connect("127.0.0.1","root","1234");
if(!$conn) die("error!");
$result=mysql_select_db("zhq",conn);
if(!$result) {
    mysql_close($conn);
    die("error!");
}
$sql="set names utf8";
$sql="update t_user set upass=' " .$upass. " 'where uname=' " .$uname. " ";
echo $sql;
$rs=mysql_query($sql);
if(!$rs){
    mysql_close($conn);
    die("error!");
}
else echo "success";
mysql_close($conn);
?>
    
//query.php
<?
$uname=$_POST['uname'];
$upass=$_POST['upass'];
if($uname==""||$upass==""){
    echo "<script>loaction.href='index.html';</script>";
}
$conn=mysql_connect("127.0.0.1","root","1234");
if(!$conn) die("error!");
$result=mysql_select_db("zhq",conn);
if(!$result) {
    mysql_close($conn);
    die("error!");
}
$sql="set names utf8";
$sql="select * from t_user";
echo $sql;
$rs=mysql_query($sql);
if(!$rs){
    mysql_close($conn);
    die("error!");
}
$recordcount=mysql_num_rows($rs);
if($recordcount>0){
    while($row=mysql_fetch_assoc($rs)){
        $uname=$row['uname'];
        $upass=$row['upass'];
        echo "($uname,$upass),";
    }
}

mysql_close($conn);
?>

NSURLSession

iOS9的数据请求变化NSURLSession。创建单视图应用程序。

//ViewController.m
#import "SVProgressHUD.h"
-(void)viewDidLoad{
    [super viewDidLoad];
    UIButton * btn=[[UIBUtton alloc]initWithFrame:CGRectMake(50,50,200,40)];
    [btn setTitle:@"开始" forState:UIControlStateNormal];
    btn.backgroundColor=[UIColor greenColor];
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(btnTap)forControlEvents:UIControlEventTouchUpInside];
    /*
    NSURLRequset * request=[NSURLRequest requestWithURL:url];
    NSData * data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];//xcode7不建议使用了已经
    if(data!=nil){
        NSLog(@"%@",[[NString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    }
   */ 
}
-(void)btnTap{
    NSURL * url=[NSURL URLWithString:@"htttp://1155.159.1.248.5666/index.html"];
    NSURLSession * session=[NSURLSession sharedSession];//回话
    NSURLSessionDataTask * task=[session dataTaskWithURL:url completionHandler:^( NSData *_Nullable data,NSURLResponse *_Nullable respon,NSError * _Nullable error{
        //对UI的操作主要,所有对UI的操作必须在主线程中
        dispatch_async(dipatch_get_main_queue(),^{
            [SVProgressHUD dismiss];//关闭 注意多线程问题
        });
        
        NSLog(@"thread!");
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    }
    )];//任务步数据请求方式
    [SVProgressHUD showWithStates:@"加载中..." maskType:SVProgressHUDMaskTypeBlack];
    [task resume];//启动任务
    NSLog(@"main thread!");
}

配置文件Info.plist添加

image-20220606170104922


iOS动态POST请求网络数据。新建单视图应用程序。

//ViewController.m
#import "SVProgressHUD.h"
-(void)viewDidLoad{
    [super viewDidLoad];
    NSURL * url=[NSURL URLWithString:@"http://115.159.1.248.56666/xinwen/getsearchs.php"];
    NSMutableURLRequset * request=[NSMutabelURLRequest requestWithURL:url];
    [request setHTTPMethod:@"post"];
    NSString * str=@"content=62";//设置参数
    [request setHTTBody:[str dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLSession * session=[NSURLSession sharedSession];//会话
    NSURLSessionDataTask * task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,NSURLReponse * _Nullable response,NSError * _Nullable error{
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    })];
    [task resume];//启动任务
    //修改配置文件允许数据传送
}

iOS9请求数据代理事件。基于事件的请求。

@interface ViewController()<NSURLSessionDataDelegate>
{
    NSMutableData * revData;
}
//ViewController.m
#import "SVProgressHUD.h"
-(void)viewDidLoad{
    [super viewDidLoad];
    NSURL * url=[NSURL URLWithString:@"http://115.159.1.248.56666/index.html"];
    NSURLSession * session=[NSURLSession sessionWithConfiguration:[NSURLSessionConnfiguration defalutSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];//会话
    NSURLSessionDataTask * task=[session dataTaskWithURL:url]
    [task resume];//启动任务
    //修改配置文件允许数据传送
}
#pragma mark - urlsessiondata
//响应
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)reponse completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
    revData=[[NSMutableData alloc]init];
    NSLog(@"回来数据!");
    completionHandler(NSURLSeesionResponseAllow);//允许响应继续,否则后面事件就被取消掉了
    
}
//开始接收数据
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *) dataTask didReceiveData:(NSData *)data{
     NSLog(@"接收数据!");
     [revData appendData:data];
}
//接收完成
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSSError *)error{
     NSLog(@"完成revData=%@, error=%@!",[[NSString alloc]initWithData:revData encoding:NSUTF8StringEncoding],eror);
}
//查看接收了多少数据,下载中才会出现
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
    NSLog(@"%lld,//%lld",bytesSent,totalBytesSent );
}

60章

数据库网络的xml解析json

xml

image-20220606203359387

#import "MFStudent.h"
@interface ViewController<NSXMLParserDelegate>
{
    NSMutableArray * students;
    MFStudent * student;
    BOOL isFound;//是否遇到一个学生节点
    NSString * proName;//学生属性
}
-(IBAction)xmlTap:(id)sender;

//ViewController.m

-(void)viewDidLoad{
    [super viewDidLoad];
    students=[[NSMutableArray alloc]initWithCapacity:100];
}

-(IBAction)xmlTap:(id)sender{
    //xml文件两种解析方式1、基于文档document(整个文件加载) 2、基于事件sax
    //xml文件完整路径
    NSString * path=[[NSBundle mainBundle]pathForResource:@"students" ofTye:@"xml"];
    NSData * data=[NSData dataWithContentsOfFile:path];//读到内存
    //NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    NSXMLParser * parser=[[NSXMLParser alloc]initWithData:data];//二进制数据创建xml转换器
    [paser setDelegate:self];//设置事件代理对象
    [parser parse];//开始转换
    
    
}
//重写五个事件
-(void)parserDidStartDocument:(NSXMLParser *)parser{//文档开始
    NSLog(@"文档开始");
    //清空集合
    [students removeAllObjects];
    isFound=NO;
    proName=@"";
}
//元素(标签)开始
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName anmespaceURL:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    NSLog(@"元素<%@>开始",elementName);
   if(isFound=YES){
       proName=elementName;
   }
   if([elementName isEqualToString:@"student"]){
       isFound=YES;
       student=[[MFStudent alloc]init];
   }
}
//发现字符串
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSSTring *)string{
    NSLog(@"preName=%@,发现字符串(%@)",proName,string);
    if(isFound==YES&&proName.length>0){//如果是学生属性
        [student setValue:string forKey:proName];//kvc赋值,对对象属性赋值的手段
        proName=@"";
    }
}
//元素(标签)结束
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName anmespaceURL:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    NSLog(@"元素<%@>结束",elementName);
    if([elementName isEqualToString:@"student"]){
        //改标记
        isFound=NO;
        //放学生集合
        [students addObject:student];
    }
    
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{//文档结束
    NSLog(@"文档结束");
    //遍历
    for(MFStudent * s in students){
        NSLog(@"name=%@,sex=%@,age=%d",s.name,s.sex,s.age);
    }
    
}
//MFStudent.m
@property (strong,nonatomic) NSString * name;
@property (strong,nonatomic) NSString * sex;
@property (assign,nonatomic) int age;
<!-- student.xml -->
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<students>
    <student>
        <name>张三</name>
        <sex></sex>
        <age>22</age>
    </student>
    <student>
        <name>李四</name>
        <sex></sex>
        <age>20</age>
    </student>
</students>

#import "MFStudent.h"
@interface ViewController<NSXMLParserDelegate>
{
    NSMUtableArray * students;
    MFStudent * student;
}
-(IBAction)xmlTap:(id)sender;
-(IBAction)longxmlTap:(id)sender;
//ViewController.m

-(void)viewDidLoad{
    [super viewDidLoad];
    students=[[NSMutableArray alloc]initWithCapacity:100];
}

-(IBAction)xmlTap:(id)sender{
    NSString * path=[[NSBundle mainBundle]pathForResource:@"students" ofTye:@"xml"];
    NSData * data=[NSData dataWithContentsOfFile:path];//读到内存
    //NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    NSXMLParser * parser=[[NSXMLParser alloc]initWithData:data];//解析器
    [paser setDelegate:self];//代理
    [parser parse];//转换
}
//重写五个事件
-(void)parserDidStartDocument:(NSXMLParser *)parser{//文档开始
    NSLog(@"文档开始");
    [students removeObjects];
}
//元素(标签)开始
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName anmespaceURL:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    NSLog(@"元素<%@>开始,attri=%@",elementName,attributeDict);
    if([elementName isEqualToString:@"student"]){
        student=[[MFStudent alloc]init];
        NSArray * arr=[attributeDict allKeys];
        for(NSString * str in arr){
            [student setValue:[attributeDic objectForKey:str] forKey:str];
        }
    }
}
//发现字符串
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSSTring *)string{
    NSLog(@"发现字符串(%@)",string);
}
//元素(标签)结束
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName anmespaceURL:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    NSLog(@"元素<%@>结束",elementName);
    if([elementName isEqualToString:@"student"]){
		[students addObject:student];
    }
    
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{//文档结束
    NSLog(@"文档结束");
    for(MFStudent * s in students){
        NSLog(@"name=%@,sex=%@,age=%d",s.name,s.sex,s.age);
    }
}

-(IBAction)longxmlTap:(id)sender{
    NSURL * url=[NSURL URLWithSting:@"http://pup.weather.sina.com.cn/xml.php"];
    NSMutableURLRequest * request=[[NSMutable alloc]initWithURL:url];
    [request setHTTPMethod:@"post"];
    NSString * str=@"citt=北京&password=DJOYniewT8234jlsk&day=0";
    NSData * data=[str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];//设置参数
    NSData * result=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSLog(@"%@",[[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding]);
}
//MFStudent.m
@property (strong,nonatomic) NSString * name;
@property (strong,nonatomic) NSString * sex;
@property (assign,nonatomic) int age;
<!-- student.xml -->
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<students>
    <student name="张三" sex="" age="22"/>
    <student name="李四" sex="" age="20"/>
</students>

访问web的xml。

image-20220606214546211


基于文档方式解析xml。使用第三方组件GDataXMLNode。拷贝文件夹工程

设置头文件搜索路径:

image-20220606215617695

增加编译参数:非ARC文件。

image-20220606215757491

增加第三方库:

image-20220606215913013
image-20220606220516211

#import "MFStudent.h"
@interface ViewController<NSXMLParserDelegate>
{
    NSMUtableArray * students;
    MFStudent * student;
}
-(IBAction)xmlTap:(id)sender;
-(IBAction)longxmlTap:(id)sender;

//ViewController.m

#import "GDataXMLNode.h"
-(void)viewDidLoad{
    [super viewDidLoad];
    students=[[NSMutableArray alloc]initWithCapacity:100];
}

-(IBAction)xmlTap:(id)sender{
    NSURL * url=[NSURL URLWithSting:@"http://localhost/web/student.xml"];
    NSURLSession * session=[NSURLSession sharedSession];
    NSURLSessionDataTask * task=[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data,NSURLResponse * _Nullable response,NSError * _Nullable error){
        NSLog(@"%@",data);
        //基于文档解析
        //创建文档
        GdataXMLDocument * doc=[[GDataXMLDocument alloc]initWithData:data options:0 error:nil];
        if(doc){
            //(@"%@",doc);
            //拿到根元素
            GDataXMLElement * rooElement=doc.rootElement;
            for(GDataXMLElement * student in rootElement.children){
                MFStudent * s=[[MFStudent alloc]init];
                for(GDataXMLElement * property in student.children){
                    [s setValue:property.stringValue forKey:property.name];
                    NSLog(@"pname=%@,pvalue=%@",property.name,property.stringValue);
                }
                [students addObject:s];
            }
            for(MFStudent * s in students){
                NSLog(@"name=%@,sex=%@,age=%d",s.name,s.sex,s.age);
            }
        }
        else{
            NSLog(@"无法解析!");
        }
       
    }];
    [task resume];
    //配置文件允许传送
}

//MFStudent.m
@property (strong,nonatomic) NSString * name;
@property (strong,nonatomic) NSString * sex;
@property (assign,nonatomic) int age;
<!-- student.xml -->
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<students>
    <student name="张三" sex="" age="22"/>
    <student name="李四" sex="" age="20"/>
</students>

json

iOS开发部分数据传送采用json格式

image-20220606221750207
image-20220606221946075
image-20220606222504810
image-20220607113038867

image-20220607113318813

-(IBAction)createTap:(id)sender;
-(IBAction)jxTap:(id)sender;
-(IBAction)phpTap:(id)sender;
//ViewController.m
#import "MFUser.h"
-(IBAction)createTap:(id)sender{
    NSDictionary * dict=[NSDicitonary dictionaryWihtObjectsAndKeys:@"张三",@"name",@"男",@"sex",@"22",@"age",nil];
   NSDictionary * dict2=[NSDicitonary dictionaryWihtObjectsAndKeys:@"李四",@"name",@"女",@"sex",@"21",@"age",nil];
   // NSLog(@"%@",dict);
   NSArray * array=[NSArray arrayWithObjects:dict,dict2,nil];
    
    NSData * data=[NSJSONSerialization dataWithJSONOBject:array options:NSJSONWriteingPrettyPrinted error:nil];//二进制数据
    NSLog(@"%@",[[NSString alloc]initWithDat:data encoding:NSUTF8StringEncoding]);
}

-(IBAction)jxTap:(id)sender{
    NSURL * url=[NSURL URLWithSting:@"http://xxx"];
    NSURLRequset * requset=[[NSURLRequset allic]initWithURL:url];
    NSData * data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data==nil){
        NSLog(@"请求数据失败");
    }
    else{
        //NSString * str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        //NSLog(@"%@",str);
        NSDictionary * dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        //NSLog(@"%@",dict);
        NSDictionary * weather=[dict objectForKey:@"weatherinfo"];
        NSDictionary * arr=[weather allKeys];
        for(NSString * str in arr){
            NSLog(@"%@=%@",str,[weather objectForKey:str]);
        }
    }
}


-(IBAction)phpTap:(id)sender{
    NSURL * url=[NSURL URLWithSting:@"http://localhost/php/select.php"];
    NSURLRequset * requset=[[NSURLRequset allic]initWithURL:url];
    NSData * data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data==nil){
        NSLog(@"请求数据失败");
    }
    else{
        //NSString * str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        //NSLog(@"%@",str);
        NSArray * array=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMUtableLeaves error:nil];
        NSMutableArray * users=[[NSMutableArray alloc]init];
        for(NSDictionary * dict int arrya){
            MFUser * user=[[MFUser alloc]init];
            NSArray * arr=[dict allKeys];
            for(NSString * str in arr){
                
                NSLog(@"%@=%@",str,[dict objectForKey:str]);
                [user setValue:[dict objectForKey:str] forKey:str];
                
                [users addObject:user];
            }
            
        }
        NSLog(@"%@",users);
    }
}


@interface
@property (strong,nonatomic)NSString * name;
@property (strong,nonatomic)NSString * pass;
@property (assign,nonatomic)int idd;
//MFUser.m

<?   //网页端从数据库查询到数据以json形式返回给移动
    $conn=mysql_connect("127.0.0.1","root","1234");//连接MySql
	if(!$conn) die("连接数据库失败!");
	$result=mysql_select_db("zhq",$conn);//指定数据库
	if(!$result){
        mysql_close($conn);
        die("指定数据库失败!");
    }
	$sql="set names utf8";
	mysql_query($sql);
	$sql="select * from t_user";
	$rs=mysql_query($sql);//运行sql
	if(!$rs){
        mysql_close($conn);
        die("查询失败!");
    }
	$recordcount=mysql_num_rows($rs);
	if($recordcount>0){
        while($row=mysql_fetch_assoc($rs)){//得到一行
            $arr[]=$row;
        }
        echo json_encode($arr);
    }
    mysql_close($conn);
?>

image-20220607111314914

原文地址:https://blog.csdn.net/m0_45020051/article/details/125169713

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_37832.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注