donljt2606
2011-08-11 15:34 阅读 295
已采纳

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"];
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    drjgk44268 drjgk44268 2011-08-11 19:13
    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.

    点赞 评论 复制链接分享

相关推荐