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

时间:2014-03-28 23:03:46

标签: 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];

3 个答案:

答案 0 :(得分:2)

有几点:

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

  2. 然后你说:

      

    产生无效结果的当前代码(来自IBAction函数)

    您的代码不会产生任何"有效结果"在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. 虽然您的初始代码示例使用的是基于委托的NSURLConnection,但您已修改了使用dataWithContentsOfURL的答案。如果您真的不想使用基于委托的NSURLConnection,请改用sendAsynchronousRequest,这样可以提供dataWithContentsOfURL的简单性,但允许您使用GET 1}}或POST请求,以及异步执行。因此,如上所示创建NSMutableURLRequest(根据您是GET还是POST使用适当的方法代码),消除实例化NSMutableData的行和NSURLConnection并将其替换为:

    [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];
    }];
    

答案 1 :(得分:0)

所以主要的问题是尝试从手机而不是模拟器中击中localhost,呃。现在成功运行的代码如下。感谢大家的帮助。

NSURL *url = [NSURL URLWithString:@"http://localhost/trendypieces/site/ios/processLatest.php?caption=mycaption"];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"GET"];

    returnData = [[NSMutableData alloc] init];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

答案 2 :(得分:0)

这里适用于带有两个变量的POST,感谢@Rob来自另一个帖子的代码。

NSURL *url = [NSURL URLWithString:@"http://192.168.1.5/trendypieces/site/ios/processLatest.php"];

    NSString *var2 = @"variable2";
    NSString *postString    = [NSString stringWithFormat:@"caption=%@&var2=%@", _captionField.text, var2];
    NSData   *postBody      = [postString dataUsingEncoding:NSUTF8StringEncoding];

    //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, any way you want to, e.g.
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];