NSURLSessionDataTask関数を使用して、PHPにデータを投稿し、JSONで応答を取得できます。
- (IBAction)saveButton:(id)sender
{
NSString *noteDataString = [NSString stringWithFormat:@"name=%@&email=%@", nameTextField.text, emailTextField.text];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:@"http://mydomain.com/iOS/Tulon/phpFile.php"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[noteDataString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *dataRaw, NSURLResponse *header, NSError *error) {
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:dataRaw
options:kNilOptions error:&error];
NSString *status = json[@"status"];
if([status isEqual:@"1"]){
//Success
} else {
//Error
}
}];
[dataTask resume];
}
次のコードを使用して、PHPで応答を処理できます。
<?php
if (isset ($_POST["name"]) && isset ($_POST["email"])){
$name = $_POST["name"];
$email = $_POST["email"];
} else {
$name = "Tulon";
$email = "[email protected]";
}
// Insert value into DB
$sql = "INSERT INTO $dbtable (name, email) VALUES ('$name', '$email');";
$res = mysql_query($sql,$conn) or die(mysql_error());
mysql_close($conn);
if($res) {
$response = array('status' => '1');
} else {
die("Query failed");
}
echo json_encode($res);
exit();
?>
これがお役に立てば幸いです