app接口

ios与php的交互2016.6

2016-06-24  本文已影响751人  cj2527

场景一.ios上传数据,提交给php,它会写入网络数据库

php把插入结果,以某种格式,例如json,发送数据给ios客户端,
ios客户端,反序列化json,也就是解析。

php端有一个insert.php接口文件,存放在服务器上,例如它的地址存放在http://127.0.0.1/php/insert.php,这个也就是接口地址了。
如果你是单独开发ios端,那么php端的程序员会告诉你这个地址,以及它提供的参数,
例如下面的userName,password。你上传的json数据的参数也是这个。
完整代码如下:

<?php
header("Content-type: application/json; charset=utf-8");
$con = mysql_connect("127.0.0.1","root","root");
if (!$con)
{
    die('Could not connect: ' . mysql_error());
}else{
    echo '连接成功';
    echo "\n";
}

mysql_select_db("my_db", $con);
mysql_query("SET NAMES 'utf8'",$con);

//获得数据
$json = file_get_contents('php://input');  
 // 反序列化JSON
$de_json = json_decode($json,TRUE);
//统计个数
$count_json = count($de_json);
//遍历json,插入到mysql数据库
for ($i = 0; $i < $count_json; $i++)
{    
    //取值
    $userName = $de_json[$i]['userName'];
    $password = $de_json[$i]['password'];
   
    //执行插入
    $result = mysql_query($sql,$con);

    if($result)
    {
        echo '成功插入';
    }else{
        echo '插入失败';
    }  
}

//关闭数据库连接
mysql_close($con);

?>

ios端,在某个方法中:

-(void)postUpload{
  
    //1.url,接口地址,php端提供的
    NSURL *url =[NSURL URLWithString:@"http://127.0.0.1/php/insert.php"];
    //2.请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:5];
    
    //2.1设置HTTP方法
    request.HTTPMethod=@"POST";
    
    //2.2上传json类型数据,本质是一个字符串
 
    //序列化:将数组、字典转为二进制
    NSDictionary *dic1 = @{@"userName":@"cj",@"password":@"27"};
    NSDictionary *dic2 = @{@"userName":@"cj2527",@"password":@"26"};
    NSArray *array = @[dic1,dic2];
    //检测能否被序列化
    if (![NSJSONSerialization isValidJSONObject:array]) {
        NSLog(@"格式不正确!");
        return;
    }
    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
    
    //3.定义Session连接
 
    NSURLSession *session = [NSURLSession sharedSession];
    NSData *data = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
    //定义上传任务
    NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error) {
                id result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
               NSLog(@"%@",result);
    }];
   //开启任务
    [task resume];
上一篇下一篇

猜你喜欢

热点阅读