php - 如何将变量从 iOS 发送到 php 文件

标签 php ios nsurl

我有一个简单的任务,通过 GET 将一个变量发送到 php 页面。我似乎找不到任何有用的东西,而且似乎都超出了我的需要。

看来我需要代码来设置 NSURL 字符串,NSURL 请求,然后执行。

有人能给我粘贴一些简单的代码来执行这样的 URL 吗:

http://localhost/trendypieces/site/ios/processLatest.php?caption=yosa

谢谢!

这是不起作用的最新迭代,看起来更接近,但实际上它会返回错误警报。不知道那个错误是什么......但是......

//construct an URL for your script, containing the encoded text for parameter value
    NSURL* url = [NSURL URLWithString:
                  [NSString stringWithFormat:
                   @"http://localhost/trendypieces/site/ios/processLatest.php?caption=yosa"]];

    NSData *dataURL =  [NSData dataWithContentsOfURL:url];
    NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];

    if([serverOutput isEqualToString:@"OK"]) {

        alertsuccess = [[UIAlertView alloc] initWithTitle:@"Posted" message:@"Done"
                                                 delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

    } else {
        alertsuccess = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Done"
                                                 delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

    }
    [alertsuccess show];

最佳答案

几点:

  1. 当您使用 initWithRequest:delegate: 创建一个 NSURLConnection 时,它会自动启动连接。 不要自己调用start 方法(在某些情况下,它会干扰初始连接)。这仅适用于当您使用 initWithRequest:delegate:startImmediately: 且最终参数为 NO 时。

  2. 然后你说:

    Current code that yields no active result (from within an IBAction function)

    您的代码不会在 IBAction 方法中产生任何“事件结果”。它会调用 NSURLConnectionDataDelegateNSURLConnectionDelegate 方法。你实现了吗?值得注意的是,确保您还实现了 connection:didFailWithError:,它会告诉您是否存在任何连接错误。

    如果您需要IBAction方法中的结果,您应该使用NSURLConnection方法sendAsynchronousRequest

  3. 转到这个问题的标题,“如何发送变量”,您应该小心地将用户输入添加到 URL。 (这不是您没有收到任何回复的直接问题,但这在将变量的内容发送到 Web 服务器时很重要。)

    值得注意的是,caption=xxx 部分,xxx 不能包含空格或保留字符,如 +& 等。您需要做的是对其进行百分比编码。所以,你应该:

    NSString *caption = ... // right now this is @"yosa", but presumably this will eventually be some variable
    
    NSMutableData *data = [[NSMutableData alloc] init];
    self.receivedData = data;
    // [data release];  // if not ARC, insert this line
    
    //initialize url that is going to be fetched.
    NSString *encodedCaption = [self percentEscapeString:caption];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost/trendypieces/site/ios/processLatest.php?caption=%@", encodedCaption]];
    
    //initialize a request from url
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //initialize a connection from request
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    self.connection = connection;
    // [connection release]; // if not ARC, insert this line
    
    // DO NOT start the connection AGAIN
    //[connection start];
    

    percentEscapeString 定义为:

    - (NSString *)percentEscapeString:(NSString *)string
    {
        NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                     (CFStringRef)string,
                                                                                     (CFStringRef)@" ",
                                                                                     (CFStringRef)@":/?@!$&'()*+,;=",
                                                                                     kCFStringEncodingUTF8));
        return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    }
    

    (注意,有一个很有前途的 NSString 方法,stringByAddingPercentEscapesUsingEncoding,它做的事情非常相似,但抵制使用它的诱惑。它处理一些字符(例如空格字符),但不是其他一些字符(例如 +& 字符)。)

  4. 最后,您说这是一个 GET 请求(这意味着您没有更改服务器上的任何内容)。如果它确实是 GET 请求,请参阅我之前的观点。但是如果这个请求真的是更新数据,你应该做一个 POST 请求(其中 caption=yosa 进入请求的主体,而不是 URL)。这还有另一个优点,因为 URL 的长度是有限制的(因此当您在 GET 请求的 URL 中提交参数时,参数可以有多长)。

    无论如何,如果你想创建一个 POST 请求,它应该是这样的:

    NSString *caption = ... // right now this is @"yosa", but presumably this will eventually be some variable
    
    NSMutableData *data = [[NSMutableData alloc] init];
    self.receivedData = data;
    // [data release];  // if not ARC, insert this line
    
    //create body of the request
    NSString *encodedCaption = [self percentEscapeString:caption];
    NSString *postString = [NSString stringWithFormat:@"caption=%@", encodedCaption];
    NSData *postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
    
    //initialize url that is going to be fetched.
    NSURL *url = [NSURL URLWithString:@"http://localhost/trendypieces/site/ios/processLatest.php"];
    
    //initialize a request from url
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPBody:postBody];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    //initialize a connection from request
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    self.connection = connection;
    // [connection release]; // if not ARC, insert this line
    
  5. 虽然您的初始代码示例使用基于委托(delegate)的 NSURLConnection,但您已经修改了您的答案以使用 dataWithContentsOfURL。如果您真的不想使用基于委托(delegate)的 NSURLConnection,请改用它的 sendAsynchronousRequest,它提供了 dataWithContentsOfURL 的简单性,但是允许您使用 GETPOST 请求,以及异步执行。因此,如上所示创建 NSMutableURLRequest(根据您是 GET 还是 POST 使用适当的方法代码),消除实例化 NSMutableDataNSURLConnection 并将其替换为:

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    
        if (!data) {
            NSLog(@"Error = %@", connectionError);
    
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Error" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
    
            return;
        }
    
        NSString *serverOutput = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    
        NSLog(@"Data = %@", serverOutput);
    
        UIAlertView *alert;
    
        if ([serverOutput isEqualToString:@"OK"]) {
            alert = [[UIAlertView alloc] initWithTitle:nil message:@"Posted" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        } else {
            alert = [[UIAlertView alloc] initWithTitle:nil message:@"Not OK" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        }
    
        [alert show];
    }];
    

关于php - 如何将变量从 iOS 发送到 php 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22724646/

相关文章:

ios - 如何在 NSUrl 中传递 * () $ 等?

iphone - 内存 RAM 中的 NSURL

php - nodejs TCP/IP 中的\r\n\r\n 是什么字符

php - 如何在 PHP 中使用 SQL 中的 if/else 语句

PHP 写入文件 - 权限被拒绝

ios - swift 2 : MBProgressHUD Refresh later Error : Terminating app due to uncaught exception 'NSRangeException'

ios - 如何创建具有不同颜色的贝塞尔曲线路径?

ios - UICollectionViewCell 子类 init 从不运行

php - Codeigniter RESTful API-{"status":false ,"error" :"Unknown method."}

iphone - 使用字符串变量打开 NSURL - iPhone