如何在没有用户的情况下将服务器授权到iOS应用程序?
我是如何在没有用户的情况下将服务器授权到iOS应用程序?,ios,objective-c,iphone,apache,authorization,Ios,Objective C,Iphone,Apache,Authorization,我是iOS编程新手。我制作了iOS应用程序,连接到MSSQL 当对服务器的联机对话框授权被停用时,它可以正常工作 因此,当我们激活授权时,我的应用程序无法工作。 如何在我的应用程序中指定授权数据? 如何在应用程序中填写登录和传递背景信息? 它是否安全 我的代码是下一个: ViewController.m 下一个错误是: 2016-01-25 17:10:50.398报告[751:22264]响应:{URL:https://*****/file.php}{状态代码:401,标题{ 连接=关闭;
iOS
编程新手。我制作了iOS
应用程序,连接到MSSQL
当对服务器的联机对话框授权被停用时,它可以正常工作
因此,当我们激活授权时,我的应用程序无法工作。
如何在我的应用程序中指定授权数据?
如何在应用程序中填写登录和传递背景信息?
它是否安全
我的代码是下一个:
ViewController.m
下一个错误是:
2016-01-25 17:10:50.398报告[751:22264]响应:{URL:https://*****/file.php}{状态代码:401,标题{
连接=关闭;
“内容长度”=484;
“内容类型”=“文本/html;字符集=iso-8859-1”;
日期=“2016年1月25日星期一14:10:50 GMT”;
Server=“Apache/2.2.3(CentOS)”;
“Www Authenticate”=“Basic realm=\”请输入登录并通过SOC\”;
}}(空)
2016-01-25 17:10:50.402报告[751:22264]响应==>
401需要授权
我的php是下一个
file.php
你的问题不太清楚,我不知道如何在应用程序中填写和传输登录信息,并将数据传递到服务器后台。这取决于你如何配置服务器。通常我们使用基本访问身份验证
,我们将其放入header@YHaiti我们进行了基本的访问验证,但应用程序无法运行。我尝试使用凭据执行NSURLSession,但401仍然出现:(@Maria你能分享你的代码吗?这样我们就可以知道你如何使用NSURLSession了。你的问题不太清楚。我不知道如何在应用程序中填写和传输登录信息,以及将数据传递到服务器后台。这取决于你如何配置服务器。通常我们使用我们放在header@YHaiti我们做了基本的空调cess身份验证,但应用程序不起作用。我尝试使用凭据执行NSURLSession,但401仍然显示:(@Maria你能分享你的代码吗?这样我们就可以看到你如何使用NSURLSession了
#import "ViewController.h"
#import "SBJson.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void) alertStatus:(NSString *)msg :(NSString *)title
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil, nil];
[alertView show];
}
- (IBAction)loginClicked:(id)sender {
NSInteger success = 0;
@try {
if([[self.txtUsername text] isEqualToString:@""] || [[self.txtPassword text] isEqualToString:@""] ) {
[self alertStatus:@"Please, enter login and password!" :@"Error" :0];
} else {
// login in app (this login is use for entrance to mssql base)
NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[self.txtUsername text],[self.txtPassword text]];
NSLog(@"PostData: %@",post);
NSURL *url=[NSURL URLWithString:@"https://*****/file.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[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];
NSURLSessionDataTask *urlData = [defaultSession dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Response:%@ %@\n", response, error);
if(error == nil)
{
NSString *text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Response ==> %@", text);
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
NSInteger *success = [jsonData[@"success"] integerValue];
NSLog(@"Success: %ld",(long)success);
if(success == 1)
{
NSLog(@"Login SUCCESS");
dispatch_async(dispatch_get_main_queue(), ^ {
[self performSegueWithIdentifier:@"goto_login" sender:self];
});
} else {
[self alertStatus:@"Login/password is wrong!" :@"Error" :0];
}
}
else
{
[self alertStatus:@"Connection error!" :@"Error!" :0];
}
}];
[urlData resume];
}
}
@catch (NSException * e) {
NSLog(@"Exception: %@", e);
[self alertStatus:@"Incorrect login/password!" :@"Error!" :0];
}
}
- (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;
dispatch_async(dispatch_get_main_queue(), ^ {
[alertView show];
});
}
- (IBAction)backgroundClick:(id)sender {
[self.txtPassword resignFirstResponder];
[self.txtUsername resignFirstResponder];
}
// for login to server
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
if(challenge.previousFailureCount == 0)
{
NSString *user = @"*****";
NSString *password = @"*****";
NSURLCredentialPersistence persistence = NSURLCredentialPersistenceForSession;
NSURLCredential *credential = [NSURLCredential credentialWithUser:user password:password persistence:persistence];
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
else
{
NSLog(@"%s: challenge.error = %@",__FUNCTION__, challenge.error);
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
}
@end
2016-01-25 17:10:50.398 Report[751:22264] Response:<NSHTTPURLResponse: 0x7fc691cf22c0> { URL: https://*****/file.php } { status code: 401, headers {
Connection = close;
"Content-Length" = 484;
"Content-Type" = "text/html; charset=iso-8859-1";
Date = "Mon, 25 Jan 2016 14:10:50 GMT";
Server = "Apache/2.2.3 (CentOS)";
"Www-Authenticate" = "Basic realm=\"Please enter login and pass for SOC\"";
} } (null)
2016-01-25 17:10:50.402 Report[751:22264] Response ==> <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
401 Authorization Required
<?php
// array for JSON response
$response = array();
// include db connect class
require_once '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
mssql_query("SET NAMES 'utf8'");
mssql_query("SET CHARACTER SET 'utf8'");
// Request type is check Login
$password=$_POST["password"];
$username=$_POST["username"];
// check for user
if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['password'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "Enter login/pass!";
die(json_encode($response));
}
$query = " SELECT * FROM users WHERE username = '$username'and password='$password'";
$sql1=mssql_query($query);
$row = mssql_fetch_array($sql1);
if (!empty($row)) {
$response["success"] = 1;
$response["message"] = "Authorization is successfull!";
die(json_encode($response));
}
else{
$response["success"] = 0;
$response["message"] = "Incorrect login/pass!";
die(json_encode($response));
}
}
else{
$response["success"] = 0;
$response["message"] = "Enter login/pass!";
die(json_encode($response));
}
mssql_close();
?>
?>
<?php
define('DB_USER', "****"); // db user
define('DB_PASSWORD', "****"); // db password (mention your db password here)
define('DB_DATABASE', "****"); // database name
define('DB_SERVER', "****"); // db server
?>
<?php
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mssql database
$con = mssql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mssql_error());
// Selecing database
$db = mssql_select_db(DB_DATABASE) or die(mssql_error()) or die(mssql_error());
// returing connection cursor
return $con;
}
function close() {
// closing db connection
mssql_close();
}
}
?>