编辑:我已经根据从人们那里得到的所有建议编辑了 OP,所以这是最新的(并且仍然无法正常工作)。
我有以下代码,它应该将一些数据发布到我拥有的 .php 文件中(然后发布到数据库,但这超出了这个问题的范围)。
对于我的方法,我传递了一个包含一些字符串的数组。
-(void)JSON:(NSArray *)arrayData {
//parse out the json data
NSError *error;
//convert array object to data
NSData* JSONData = [NSJSONSerialization dataWithJSONObject:arrayData
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *JSONString = [[NSString alloc] initWithData:JSONData
encoding:NSUTF8StringEncoding];
NSString *URLString = [NSString stringWithFormat:@"websitename"];
NSURL *URL = [NSURL URLWithString:URLString];
NSLog(@"URL: %@", URL);
NSMutableURLRequest *URLRequest = [NSMutableURLRequest requestWithURL:URL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[JSONString UTF8String] length:[JSONString length]];
NSString *requestDataString = [[NSString alloc] initWithData:requestData
encoding:NSUTF8StringEncoding];
NSLog(@"requestData: %@", requestDataString);
[URLRequest setHTTPMethod:@"POST"];
NSLog(@"method: %@", URLRequest.HTTPMethod);
[URLRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[URLRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[URLRequest setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[URLRequest setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:URLRequest delegate:self];
if (connection) {
NSMutableData *receivedData = [[NSMutableData data] retain];
NSString *receivedDataString = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
NSLog(@"receivedData: %@", receivedDataString);
}
//potential response
NSData *response = [NSURLConnection sendSynchronousRequest:URLRequest returningResponse:nil error:nil];
//convert response so that it can be LOG'd
NSString *returnString = [[NSString alloc] initWithData:response encoding:NSASCIIStringEncoding];
NSLog(@"RETURN STRING: %@", returnString);
}
注意:我在代码中有我网站的实际 URL,以便任何人都可以测试是否愿意。
然后是 .php 方面的事情,我所要做的就是寻找任何输入(但我什么也没得到)。
<html>
<body>
<?php
echo "Connection from iOS app to MySQL database<BR>";
echo '<pre>'.print_r($GLOBALS,true).'</pre>';
?>
</body>
</html>
我现在真正想做的就是确认数据正在通过,通过将其回显到页面,然后从我的应用程序中读取页面(到目前为止数据尚未显示)。
.php 的输出:
<html>
<body>
Connection from iOS app to MySQL database<BR>'Array
(
)
'<pre>Array
(
[_GET] => Array
(
)
[_POST] => Array
(
)
[_COOKIE] => Array
(
)
[_FILES] => Array
(
)
[GLOBALS] => Array
*RECURSION*
)
</pre> </body>
</html>