タイトルの通り..
JSON 用の私の NSDictionary initWithObjectsAndKeys は、POST メソッドを使用して、PHP コードを介して MySQL クエリを実行します。
私のXcodeコード:
-(IBAction)setJsonFromData:(id)sender
{
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys: @"Welcome", @"title", @"Hello", @"article", @"123456789", @"timestamp", nil];
if([NSJSONSerialization isValidJSONObject:jsonDict])
{
NSError *error = nil;
NSData *result = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
if (error == nil && result != nil) {
[self postJSONtoURL:result];
}
}
}
-(id)postJSONtoURL:(NSData *)requestJSONdata
{
NSURL *url = [NSURL URLWithString:@"http://test.com/json.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestJSONdata length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestJSONdata];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"RESULT: %@", requestJSONdata);
if (error == nil)
return result;
return nil;
}
私のPHPコード:
if (isset($_REQUEST))
{
$json = $_REQUEST;
$data = json_decode($json);
$title = $_REQUEST['title'];
$article = $_REQUEST['article'];
$timestamp = $_REQUEST['timestamp'];
mysql_query("INSERT INTO news (title, article, timestamp) VALUES ('$title->title','$article->article','$timestamp->timestamp')");
}
mysql_close();