如何将php web文件中的数据提取到objective C
这个问题我已经解决了一段时间了,所以我非常感谢你的帮助。我对iOS应用程序编程非常陌生。我已经开始使用登录应用程序,但在从php文件获取响应时,在获取“登录成功状态”时遇到了一些问题。我刚得到“登录失败”。我要给你我的密码。请纠正我的错误。 (ViewController.m)文件代码//如何将php web文件中的数据提取到objective C,php,ios,objective-c,Php,Ios,Objective C,这个问题我已经解决了一段时间了,所以我非常感谢你的帮助。我对iOS应用程序编程非常陌生。我已经开始使用登录应用程序,但在从php文件获取响应时,在获取“登录成功状态”时遇到了一些问题。我刚得到“登录失败”。我要给你我的密码。请纠正我的错误。 (ViewController.m)文件代码// #import "ViewController.h" #import "SBJson.h" @interface ViewController () @end @i
#import "ViewController.h"
#import "SBJson.h"
@interface ViewController ()
@end
@implementation ViewController
-(void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)signinclicked:(id)sender
{
NSInteger success=0;
@try {
if([[self.txtusername text] isEqualToString:@""] || [[self.txtpassword text] isEqualToString:@""] ) {
[self alertStatus:@"Please enter Email and Password" :@"Sign in Failed!" :0];
} else {
NSString *post =[[NSString alloc]initWithFormat:@"username=%@ & password=%@", [self.txtusername text],[self.txtpassword text]];
NSLog(@"PostData: %@",post);
NSURL *url=[NSURL URLWithString:@"http://shiv.9gem.net/alka/index1.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long) [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"Response ==> %@", responseData);
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
success = [jsonData[@"success"] integerValue];
NSLog(@"Success: %ld",(long)success);
if(success == 1)
{
NSLog(@"Login SUCCESS");
} else {
NSString *error_msg = (NSString *) jsonData[@"error_message"];
[self alertStatus:error_msg :@"Sign in Failed!" :0];
}
} else {
//if (error) NSLog(@"Error: %@", error);
[self alertStatus:@"Connection Failed" :@"Sign in Failed!" :0];
}
}
}
@catch (NSException * e) {
NSLog(@"Exception: %@", e);
[self alertStatus:@"Sign in Failed." :@"Error!" :0];
}
if (success) {
[self performSegueWithIdentifier:@"login_success" sender:self];
}
}
- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil, nil];
alertView.tag = tag;
[alertView show];
}
- (IBAction)backgroundtap:(id)sender {
[self.view endEditing:YES];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
@end
***( php file code)***
<?php
header('content-type:application/json');
$dbhost = 'localhost';
$dbuser = 'shiv9gem_alka';
$dbpass = 'alankritasharma';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT username,password FROM student';
mysql_select_db('shiv9gem_project');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo json_encode($row);
}
echo "Fetched data successfully\n";
if($_POST)
{
if($_POST['username']=='alankrita' && $_POST['password']=='isha123')
{
echo '{"success":1}';
}
else
{
echo '{"success":0,"error_message":"username and/or password is invalid."}';
}
} else
{
echo '{"success":0,"error_message":"username and/or password is invalid."}'; }
mysql_close($conn);?>
#导入“ViewController.h”
#导入“SBJson.h”
@界面视图控制器()
@结束
@实现视图控制器
-(无效)viewDidLoad
{
[超级视图下载];
//加载视图后,通常从nib执行任何其他设置。
}
-(无效)未收到记忆警告
{
[超级记忆警告];
//处置所有可以重新创建的资源。
}
-(iAction)已签名:(id)发件人
{
NSInteger成功率=0;
@试一试{
if([[self.txtextername text]IseQualtString:@”“][[self.txtpassword text]IseQualtString:@”“])){
[自我提醒状态:@“请输入电子邮件和密码”:@“登录失败!”:0];
}否则{
NSString*post=[[NSString alloc]initWithFormat:@“用户名=%@&密码=%@”,[self.txtsername文本],[self.txtpassword文本];
NSLog(@“PostData:%@”,post);
NSURL*url=[NSURL URLWithString:@”http://shiv.9gem.net/alka/index1.php"];
NSData*postData=[post数据使用编码:NSASCIIStringEncoding allowLossyConversion:是];
NSString*postLength=[NSString stringWithFormat:@“%lu”,(无符号长)[postData长度]];
NSMutableURLRequest*请求=[[NSMutableURLRequest alloc]init];
[请求设置url:url];
[请求设置HttpMethod:@“POST”];
[请求设置值:HttpHeaderField的postLength:@“内容长度”];
[请求设置值:@“应用程序/json”用于HttpHeaderField:@“接受”];
[请求设置值:@“应用程序/x-www-form-urlencoded”forHTTPHeaderField:@“内容类型”];
[请求setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHttpSCCertificate:YES for主机:[url主机]];
NSError*error=[[NSError alloc]init];
NSHTTPURLResponse*响应=nil;
NSData*urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&响应错误:&错误];
NSLog(@“响应代码:%ld”,(长)[响应状态代码]);
如果([response statusCode]>=200&&[response statusCode]<300)
{
NSString*responseData=[[NSString alloc]initWithData:urlData编码:NSUTF8StringEncoding];
NSLog(@“响应==>%@”,响应数据);
n错误*错误=nil;
NSDictionary*jsonData=[NSJSONSerialization
JSONObjectWithData:urlData
选项:NSJSONReadingMutableContainers
错误:&错误];
success=[jsonData[@“success”]integerValue];
NSLog(@“成功:%ld”,(长)成功);
如果(成功==1)
{
NSLog(@“登录成功”);
}否则{
NSString*错误消息=(NSString*)jsonData[@“错误消息”];
[自我提醒状态:错误消息:@“登录失败!”:0];
}
}否则{
//if(error)NSLog(@“error:%@”,error);
[自我提醒状态:@“连接失败”:@“登录失败!”:0];
}
}
}
@捕获(N例外*e){
NSLog(@“异常:%@”,e);
[自我提醒状态:@“登录失败”。:@“错误!”:0];
}
如果(成功){
[self-PerformsgueWithIdentifier:@“登录成功”发件人:self];
}
}
-(void)alertStatus:(NSString*)msg:(NSString*)title:(int)标记
{
UIAlertView*alertView=[[UIAlertView alloc]initWithTitle:title
信息:msg
代表:赛尔夫
取消按钮:@“确定”
其他按钮类型:无,无];
alertView.tag=标签;
[警报视图显示];
}
-(iAction)背景点击:(id)发送者{
[自视图编辑:是];
}
-(BOOL)textField应返回:(UITextField*)textField{
[textField resignFirstResponder];
返回YES;
}
@结束
***(php文件代码)***
我可以在您的代码中看到一些不好的做法,例如不进行异步请求或不将服务器请求层与控制器层分离
抛开这些,我建议您阅读有关模型-视图-控制器模式的内容(了解此模式:)
RestKit()是一个用于iOS的框架,旨在与restfulweb服务进行交互。你可以在RyanWenderlich网站上查看这个有用的教程
希望有帮助 非常感谢你的帮助。我一定会试试你的建议。