iPhone IOS:PHP脚本需要花费太多时间来执行?

I'm trying to run a php script in my app that will check the user's login variables against those in the database. The code below is how i am executing the file. I am running the script and then storing the result in arrays. a "yes" result means the user's login data is correct, a "no" result means it's incorrect.

This code works, however my issue is the time. I have set up timers and it takes 8 seconds to execute the first block even if my php file is BLANK. Everything else, even loading the next page is much faster (3 seconds tops)

//first block
NSString * post = [NSString stringWithFormat:@"userId=%@&password=%@",userId.text,password.text];
NSString * hostStr = @"http://domain.com/check_login.php?";
hostStr = [hostStr stringByAppendingString:post];       
NSURL *location = [NSURL URLWithString:hostStr];
NSDictionary *dictionaryData = [[ NSDictionary alloc ] initWithContentsOfURL:location ];

//second block
NSArray *resultArray = [dictionaryData objectForKey:@"result"];

NSArray *loginidArray = [dictionaryData objectForKey:@"loginid"];

NSArray *usernameArray = [dictionaryData objectForKey:@"username"];

As well during the first block of code, about 1 out of 4 times, i get this error "SendDelegateMEssage: delegate failed to return after waiting 10 seconds. main run loop mode: _kCFURLConnectionPrivateRunLoopMode". I've been trying to look it up, but i don't know what it means in according to my code. When i get this error, the code can take 30-60 seconds to execute!!!

Any direction would be appreciated.

Thanks,

Amanda

edit to include PHP, incase it's helpful to know what's happening serverside in the code.

<?php
header('Content-type: text/xml');
session_start();
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist SYSTEM \"file://localhost/System/Library/DTDs/PropertyList.dtd\">
<plist version=\"1.0\">
";

$username = "user";
$password = "pass";
$host = "localhost";
$database = "database";

// Make the connect to MySQL or die
// and display an error.
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
error_log("CANT CONNECT DB"); 
}
else
{
error_log("DB CONNECTED");
}


mysql_select_db ($database);


    $userId     = $_GET['userId'];
    $password   = $_GET['password'];


    $sql = "SELECT user_login_id,userid from user_login WHERE userId ='". $userId ."'   AND password ='".$password."'";
    $rs_login = mysql_query($sql, $link) or die (mysql_error());

    if(mysql_num_rows($rs_login) ==1)
    {

        $row = mysql_fetch_array($rs_login ); 
        $user_login_id = $row['user_login_id']; 
        $user_login_name = $row['userid'];

    // The data that needs to be transferred:
    $my_data = array();

    $my_data["result"]      = array("YES");
    $my_data["loginid"]     = array($user_login_id);
    $my_data["username"]     = array($user_login_name);

    // Open the dictionary
    echo "<dict>
";

    // Putting the data into the plist format
    foreach ($my_data as $key => $array) 
    {
    // Loop for every value in $my_data
    echo "    <key>$key</key>
    <array>
"; // Make a key with the key from $my_data and open an array for it's values.
    foreach ($array as $value) 
    { // Go through every value in the current array from $my_data
        echo "        <string>$value</string>
"; // Print the value as a string in  the array
    }
    echo "    </array>
"; // Close the array
    }

    echo "</dict>
</plist>
"; // Close the dictionary & plist 

}
else
{
    $my_data["result"] = array("NO");
    $my_data["loginid"] = array("--");
    $my_data["username"]     = array("--");

    // Open the dictionary

    echo "<dict>
";

    // Putting the data into the plist format
    foreach ($my_data as $key => $array) 
    {
    // Loop for every value in $my_data
    echo "    <key>$key</key>
    <array>
"; // Make a key with the key from $my_data and open an array for it's values.
    foreach ($array as $value) 
    { // Go through every value in the current array from $my_data
        echo "        <string>$value</string>
"; // Print the value as a string in the array
    }
    echo "    </array>
"; // Close the array
    }
    echo "</dict>
</plist>
"; // Close the dictionary & plist



}
mysql_free_result($rs_login);

?>


Solution
Here's what I went with, and it only takes 4 seconds for log in now...thanks guys.

NSHTTPURLResponse * response = nil;
NSError* error = nil;

NSString * post = [NSString stringWithFormat:@"userId=%@&password=%@",userId.text,password.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL: [NSURL URLWithString:@"http://domainname.com/check_login.php?"]];

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request 
                                           returningResponse:&response 
                                                       error:&error];
NSString *result = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];


NSString *errorDesc = nil;
NSPropertyListFormat format;

NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
                                      propertyListFromData:returnData
                                      mutabilityOption:NSPropertyListMutableContainersAndLeaves
                                      format:&format
                                      errorDescription:&errorDesc];
if (!temp) {
    NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
}

NSArray *resultArray = [temp objectForKey:@"result"];

NSArray *loginidArray = [temp objectForKey:@"loginid"];

NSArray *usernameArray = [temp objectForKey:@"username"];
dongmei5168
dongmei5168 这里有一些建议:stackoverflow.com/questions/3527051/...
大约 9 年之前 回复
donglv1831
donglv1831 这听起来似乎是正确的......但是由于你的行为不一致,我仍然建议发布你的PHP,也许有人会看到一个有待改进的地方?
大约 9 年之前 回复
duanmu2013
duanmu2013 输出包含在<plist>标记中。它看起来就像你给出的例子。
大约 9 年之前 回复
dougu3290
dougu3290 因为你在你的脚本中构建它,可能在某些情况下它可能没有完全形成,并导致字典创建被绊倒?它是否包含在<plist>标签中?(ala:developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/...)
大约 9 年之前 回复
dounuo1881
dounuo1881 输出是xml。php脚本从登录数据库获取数据并输出为xml。
大约 9 年之前 回复
duanfengwang9157
duanfengwang9157 出于我自己的好奇心,输出格式如何使您能够直接从中形成字典?在我的Web服务中,我通常输出JSON,然后使用解析器转换为字典。而且,如果您发布PHP也可能有所帮助
大约 9 年之前 回复
dougutuo9879
dougutuo9879 一秒......甚至没有。就像我说的,访问这个文件需要花费很多时间,即使文件是空白的。
大约 9 年之前 回复
doutuo1939
doutuo1939 尝试从桌面Web浏览器访问该文件时,服务器响应需要多长时间?
大约 9 年之前 回复

1个回答



  NSString * res = nil; 
NSHTTPURLResponse * response = nil;
NSError * error = nil;

NSString * post = [NSString stringWithFormat:@“userId =%@&amp; password =%@”,userId.text,password.text];
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString * postLength = [NSString stringWithFormat:@“%d”,[postData length]];

NSMutableURLRequest * request = [[[NSMutableURLRequest alloc] init] autorelease];
[请求setURL:[NSURL URLWithString:@“http:/ /domain.com/check_login.php"]];

[request setHTTPMethod:@“POST”];
[请求setValue:postLength forHTTPHeaderField:@“Content-Length”];
[请求setValue:@ “application / x-www-form-urlencoded”forHTTPHeaderField:@“Content-Type”];
[请求setHTTPBody:postData];

NSData * returnData = [NSURLConnection sendSynchronousRequest:request
returnsResponse:&amp; response \ n错误 :&amp; error];
NSString * result = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
</ code> </ pre>

我实际上只是在做同样的事情 上面代码的事情,我需要不到一秒钟。 试一试!</ p>

还可以尝试通过浏览器访问 check_login.php </ strong>,看看是否需要很长时间才能加载。 如果是这样的话,那就是导致问题的PHP文件。 如果它立即加载(就像它应该),那就是你的Objective-C代码。</ p>
</ div>

展开原文

原文

NSString* res = nil;
NSHTTPURLResponse * response = nil;
NSError* error = nil;

NSString * post = [NSString stringWithFormat:@"userId=%@&password=%@",userId.text,password.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL: [NSURL URLWithString:@"http://domain.com/check_login.php"]];

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request 
                                        returningResponse:&response 
                                        error:&error];
NSString *result = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

I am actually just doing kind of the same thing with the code above and it takes me less than a second. Give it a try!

Also try accessing your check_login.php through your browser and see if it takes long to load. If that's the case it's your PHP file that is causing the issue. If it loads instantly (like it should) it's your Objective-C code.

douwen1915
douwen1915 你什么意思? 你试过我的代码片段了吗? 因为它只是调用你的网页并将结果放在NSString * result = ....所以尝试将结果放在NSLog中以查看你得到的内容。 如果一切顺利,它将显示您的XML输出。
大约 9 年之前 回复
dongyang7152
dongyang7152 ...按照你的例子,将$ _GET更改为$ _REQUEST,就像Robot建议的那样...我如何存储结果以便我可以访问这些字段? 我试过“NSDictionary * dictionaryData = [[NSDictionary alloc] initWithContentsOfFile:result];” ,但是当我尝试访问resultArray的索引0时,我得到一个(null)值。
大约 9 年之前 回复
dtol41388
dtol41388 如果你这样做,记得把$ _GET改为$ _POST或$ _REQUEST
大约 9 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐