防止UIButton操作多次运行

时间:2014-05-23 14:34:33

标签: php mysql ios objective-c uibutton

我在故事板中的视图上设置了 UIButton ,并链接到某个操作。该操作运行一些代码,通过NSURLSessionDataTask调用PHP页面(然后在MySql DB中记录记录)。

当我触摸按钮一次并在XCode的日志屏幕中看到日志打印时,我可以看到我的打印消息一次,但如果我检查MySql DQ,我可以看到插入了多个相同的记录。

我起初认为可能是PHP代码,但如果我直接通过网络浏览器加载php页面,我就不会遇到问题,只有在通过ios代码运行时才会出现问题。

反正停止按钮代码执行的次数是多少?

来自UIButtons行动的代码:

- (void)UpdateActions{

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://xxx/mobilescript/setactions.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

    NSString *postString = [[NSString alloc] initWithFormat:@"imgname=%@",imageName];
    NSString *clearPost = [postString stringByReplacingOccurrencesOfString:@"var=" withString:@""];

    [request setHTTPBody:[clearPost dataUsingEncoding:NSUTF8StringEncoding]];
    [request setValue:clearPost forHTTPHeaderField:@"Content-Length"];
    [NSURLConnection connectionWithRequest:request delegate:self];

    NSURLSession *session = [NSURLSession sharedSession];

     NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSString * returnStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",returnStr);
    }];
    [task resume];
}

PHP代码:

<?php
    include_once("DB_SETTING.php"); //Includes DB settings

    $DB_HANDLE = mysql_connect( "$DB_SERVER" , "$DB_USERNAME" , "$DB_PASSWORD" ) or $errors[] = mysql_error();
    if(!mysql_select_db( "$DB_NAME" ))
    {
        $errors[] = "Unable to select database $DB_NAME";
    } 

    if($errors){
        echo '<pre>';
        foreach($errors as $result) {
            echo $result . ' <br>';
        }
        echo '</pre>';
    }

    //Check all settings are in place
    if(!isset($_REQUEST["imgname"]) )
    {
        echo("-1");
    }
    else
    {
            $sql = "INSERT INTO  `WS_ACTIONS` (  `ID` ,  `imgid` ,`memberid` ) 

                    SELECT 0,tb3.id,tb2.id FROM  WS_MEMBERS tb2,WS_IMAGES tb3 WHERE `IMGNAME` = '".$_REQUEST["imgname"]."' and tb2.email = '".$_REQUEST["email"]."' And NOT EXISTS (
            SELECT 
                tb1.ID 
            FROM 
                WS_ACTIONS tb1 
            inner join 
                WS_IMAGES tb2 
            on 
                tb2.id = tb1.imgid
            inner join 
                WS_MEMBERS tb3
            on 
                tb3.id = tb1.memberid
            where 
                imgname = '".$_REQUEST["imgname"]."' 
            and 
                tb3.email = '".$_REQUEST["email"]."' 
            )";
            mysql_query($sql);
            echo($sql);
    }
?>

2 个答案:

答案 0 :(得分:0)

如果您有按钮实例,则可以启用/禁用它。其他解决方案是创建一个BOOL来保持按钮是否应该执行某些事情

示例:

- (void)UpdateActions{

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://xxx/mobilescript/setactions.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

    NSString *postString = [[NSString alloc] initWithFormat:@"imgname=%@",imageName];
    NSString *clearPost = [postString stringByReplacingOccurrencesOfString:@"var=" withString:@""];

    [request setHTTPBody:[clearPost dataUsingEncoding:NSUTF8StringEncoding]];
    [request setValue:clearPost forHTTPHeaderField:@"Content-Length"];
    [NSURLConnection connectionWithRequest:request delegate:self];

    NSURLSession *session = [NSURLSession sharedSession];

     // disable your button if you have a reference to it
     [self.yourBtn setEnabled:NO]; // or set your BOOL to NO here
     NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
     // regardless of the response once your request had finished just enable your button again
        [self.yourBtn setEnabled:YES]; // or set your BOOL to YES here
        NSString * returnStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",returnStr);
    }];
    [task resume];
} 

修改 您可以尝试使用NSURLConnection,而不是这样:

- (void)UpdateActions{

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://xxx/mobilescript/setactions.php"]];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

        NSString *postString = [[NSString alloc] initWithFormat:@"imgname=%@",imageName];
        NSString *clearPost = [postString stringByReplacingOccurrencesOfString:@"var=" withString:@""];

        [request setHTTPBody:[clearPost dataUsingEncoding:NSUTF8StringEncoding]];
        [request setValue:clearPost forHTTPHeaderField:@"Content-Length"];
        [NSURLConnection connectionWithRequest:request delegate:self];

         // disable your button if you have a reference to it
         [self.yourBtn setEnabled:NO]; // or set your BOOL to NO here

         // create NSOperation to run your request on background
         NSOperationQueue *queue = [[NSOperationQueue alloc]init];
         // run your request on this peration queue
         [NSURLConnection sendAsynchronousRequest:request 
                                       queue:queue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        NSString * returnStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",returnStr);
         // do whatever you want with the response 

       [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        // Main thread work (UI usually)
        [self.yourBtn setEnabled:YES];
    }];

    }];

    } 

答案 1 :(得分:0)

问题是您正在向服务器发起两个请求。使用此行创建请求时,

[NSURLConnection connectionWithRequest:request delegate:self];

这会立即从您的服务器开始下载。然后,通过使用此行创建NSURLSessionDataTask(然后调用[task resume]),从服务器开始另一次下载,

NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

如果你正在使用NSURLSession,你也不应该调用connectionWithRequest:delegate:,所以删除该行应该可以解决你的问题。