Je kunt de NSURLSessionDataTask-functie gebruiken om gegevens tot aan PHP te posten en een reactie te krijgen met 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];
}
en je kunt het antwoord in PHP afhandelen met deze code:
<?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();
?>
Ik hoop dat dit helpt