【问题标题】:Sending an NSMutable Array to a php script in iOS将 NSMutable 数组发送到 iOS 中的 php 脚本
【发布时间】:2012-02-19 18:45:59
【问题描述】:

我正在制作一个 iPhone 应用程序,它需要将几个数组发送到一个 php 脚本,然后 php 脚本需要获取这些数组的值并编写一个 xml 文件。我知道如何用 php 编写 xml 文件,但我不确定如何将数据从 iOS 应用程序发送到 php 脚本...

是否甚至可以从 iOS 向 php 脚本发送几个整数参数?抱歉,我对 php 和 iOS 很陌生(一般来说就是编程)。

谢谢

【问题讨论】:

    标签: php iphone xml argument-passing


    【解决方案1】:

    从 iOS 应用发出 GET 或 POST 请求

    示例:

    NSURL *url = [NSURL URLWithString:@"http://www.site.com/sendData.php"];
    
            NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url 
                                                                      cachePolicy:NSURLRequestReloadIgnoringCacheData 
                                                                  timeoutInterval:60];
    
            [theRequest setHTTPMethod:@"POST"];     
            [theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
            NSString *postData = [NSString stringWithFormat:@"name1=%@&name2=%@", data1, data2];
    
            NSString *length = [NSString stringWithFormat:@"%d", [postData length]];    
            [theRequest setValue:length forHTTPHeaderField:@"Content-Length"];  
    
            [theRequest setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];
    
            NSURLConnection *sConnection = [NSURLConnection connectionWithRequest:theRequest delegate:self];    
            [sConnection start];
    

    为了下载 URL 的内容,应用程序需要 提供一个委托对象,该对象至少实现以下内容 委托方法:connection:didReceiveResponse:, 连接:didReceiveData:,连接:didFailWithError:和 connectionDidFinishLoading:.

    about NSURLConnection about NSURLRequest

    【讨论】:

      【解决方案2】:

      Tyler,你可以使用下面这段代码来发布数据。

      [NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:<your php url>];
      [urlRequest setHTTPMethod:@"POST"];
      [urlRequest setHTTPBody:@"var1=val1&var2=val2"]; //Replace with your actual name/parm values
      [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
      

      为了发送一个 NSMutableArray 数组,你应该迭代数组并构造一个包含数组字符串表示的 NSString 对象。然后你必须将该字符串设置为 http 正文。

      【讨论】:

        【解决方案3】:

        最好使用 NSMutableArrays 作为 JSON 向您的站点发送 POST 请求。

        查看适用于 JSON 的 JSONKit 框架和适用于 HTML 请求的 ASIHTTPRequest。

        https://github.com/johnezang/JSONKit

        http://allseeing-i.com/ASIHTTPRequest/

        【讨论】:

          猜你喜欢
          • 2012-06-15
          • 2012-02-18
          • 2017-08-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-06
          • 2014-12-10
          • 1970-01-01
          相关资源
          最近更新 更多