Sending an NSMutable Array to a php script in iOS

萝らか妹 提交于 2019-12-12 15:33:59

问题


I am making an iPhone app which needs to send a couple of arrays to a php script and then the php script needs to take the value(s) of those arrays and write an xml file. I know how to write the xml file with php, but I am unsure how to send the data to the php script from the iOS app...

Is it even possible to send a php script a couple of integer arguments from iOS? Sorry I am very new to php and iOS (programming in general for that matter).

Thanks


回答1:


make GET or POST request from iOS app

example:

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

In order to download the contents of a URL, an application needs to provide a delegate object that, at a minimum, implements the following delegate methods: connection:didReceiveResponse:, connection:didReceiveData:, connection:didFailWithError: and connectionDidFinishLoading:.

about NSURLConnection about NSURLRequest




回答2:


Tyler, you can use the following piece of code to post data.

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

In order to send an NSMutableArray array, you should iterate the array and construct an NSString object containing the string representation of the array. Then you must set that string as the http body.




回答3:


Would probably be best to send a POST request to your site with the NSMutableArrays as JSON.

Checkout the JSONKit framework for JSON and ASIHTTPRequest for HTML Requests.

https://github.com/johnezang/JSONKit

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



来源:https://stackoverflow.com/questions/9022108/sending-an-nsmutable-array-to-a-php-script-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!