我的内部有一个.php文件:
<?php print_r($_POST); ?>
<?php
//create short variable names
$message_txt=strip_tags($_POST['message_txt']."\n\n".json_encode($_POST), "<p>");
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'To: thing<emailaddress@email.com>' . "\r\n";
$headers .= 'From: Website <email@website.com>';
mail($toaddress, "THING Website", $message_txt, $headers);
我想从textView中获取文本并通过此php发送。有关如何实现这一目标的任何想法? 感谢
答案 0 :(得分:1)
首先,您需要在swift中使用此代码,以便将变量解析为php文件。我会告诉你代码,然后一步一步地向你解释。
这里是Swift的代码:
func HttpRequest() {
let myUrl = NSURL(string: "http://yourUrl.de/yourPhpScript.php");
let request = NSMutableURLRequest(URL: myUrl!);
request.HTTPMethod = "POST";
let postString = "Message=\(textView.text)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json {
var resultValue = parseJSON["status"] as? String
print("result: \(resultValue)")
if(resultValue=="Success")
{
// If result from php is success, do something...
}
else
{
// if result from php failed, do something...
}
dispatch_async(dispatch_get_main_queue(), {
//Display alert with confirmation.
let myAlert = UIAlertController(title: "Alert", message: "Your message", preferredStyle: UIAlertControllerStyle.Alert);
let OkAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default){ action in
}
myAlert.addAction(OkAction)
self.presentViewController(myAlert, animated: true, completion: nil);
});
}
} catch {
// report error
}
}
task.resume()
}
让我们从解释开始:
request.HTTPMethod
设置为POST
,因为您想将某些内容发布到php文件中if let parseJSON
中将是来自php脚本的重新解析值的值,如果ASYNC返回值,则可以使用该值,不要在它赢得之前放置它现在是php文件:
<?php
// If you want to connect to a server you have to do that
$servername = "";
$username = "";
$passwordServer = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $passwordServer, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset ($_POST["Message"]){
$YourMessageFromSwift = $_POST["Message"];
}
// do what you want using php
$returnValue["status"] = "Success";
echo json_encode($returnValue);
mysqli_close($verbindung);
?>
<强>解释强>
$_POST["Message"]
与swift文件中的相同希望这有助于所有人:)