gpt4 book ai didi

php - mysql数据库中的Swift数组

转载 作者:行者123 更新时间:2023-11-28 12:52:32 25 4
gpt4 key购买 nike

我正在使用代码将字符串数组(包含 HTML 代码和图像名称)发送到 mysql:

    func uploadNote(user: String, title: String, category: String, content: [String]) {
let URL: NSURL = NSURL(string: "http://site/uploadNote.php")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"

var data = NSData()
var obj: AnyObject = "l"
do {

data = try NSJSONSerialization.dataWithJSONObject(content, options: NSJSONWritingOptions.init(rawValue: 0))
obj = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
print("created data")
} catch {

}

let bodyData = "category=\(category)&username=\(user)&title=\(title)&content=\(obj)"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
print("appended data to body")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error task -> \(error)")
return
}
do {
let result = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(result)
} catch {
print("Error -> \(error)")
}

}

task.resume()
}

我必须将它存储在 mysql 中,所以我序列化这个数组并发送到 mysql(TEXT):

    $jsonContent = mysql_real_escape_string($_POST['content']);

最后我想把它发回 iPhone,所以我请求它并从 php 发送它:

while($row = mysqli_fetch_array($result)) {
$snd = (array)htmlspecialchars($row['content']);
echo json_encode($snd);
}

这是 iPhone 的代码:

func downloadNote(user: String, title: String, completionHandler: CompletionHandlerNotes) {
let URL: NSURL = NSURL(string: "http://site/downloadNotes.php")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
let bodyData = "username=\(user)&title=\(title)"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);

let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error task -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! [String]
print(result.count)
for var i = 0; i<result.count; i++ {
print("COUNT: \(i) \n \(result[i]) \n\n ")
}
//completionHandler(strArray: result)
} catch {
print("Error -> \(error)")
}

}

task.resume()

}

它返回一个计数为 1 的数组。看起来像这样:

计数:0
(
"<!DOCTYPE html PUBLIC\"-//W3C//DTD HTML 4.01//EN\"\"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\“内容=\"文本/html; charset=utf-8\">\n<meta http-equiv=\"Content-Style-Type\"; content=\"text/css\">\n<title></title>\n<meta name=\"Generator\"; content=\"Cocoa HTML Writer\">\n<style type=\"text/css\">\np.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 15.0px '.SF UI Text';颜色:#ffffff}\nspan.s1 {字体系列:'Helvetica';字体粗细:正常;字体样式:正常;字体大小:12.00pt;颜色:#000000}\nspan.s2 {字体系列:'.SFUIText-Regular';字体粗细:正常;字体样式:正常;字体大小:15.00pt;背景色:#555555}\nspan.s3 {字体系列:'.SFUIText-Regular';字体粗细:正常;字体样式:正常;字体大小:15.00pt;背景颜色:#969600}\n</style>\n</head>\n<body>\n<p class=\"p1\"> " 474472.jpg",
"<!DOCTYPE html PUBLIC\"-//W3C//DTD HTML 4.01//EN\"\"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\“内容=\"文本/html; charset=utf-8\">\n<meta http-equiv=\"Content-Style-Type\"; content=\"text/css\">\n<title></title>\n<meta name=\"Generator\"; content=\"Cocoa HTML Writer\">\n<style type=\"text/css\">\np.p1 {margin: 0.0px 0.0px 0.0px 0.0px;字体:12.0px Helvetica}\nspan.s1 {字体系列:'Helvetica';字体粗细:正常;字体样式:正常;字体大小:12.00pt}\n</style>\n</head>\n<body>\n<p class=\"p1\"> )

最佳答案

在您的 Swift 上传代码中:

  1. 获取“内容”并将其转换为 JSON
  2. 对 JSON 进行 Base64 编码
  3. 将 Base64 编码的数据附加到请求中。

在 PHP 中:

<?php
// uploadr.php
require_once 'log.php';

class Handler {
use Logger;

public function handleRequest($arg) {

try {
$this->log(__METHOD__);
$this->log(print_r($arg, true));
$json = base64_decode($arg['content']);
$this->log($json);
// just write to a file
file_put_contents('data.json', $json);
}
catch(PDOException $e) {
$this->log('Failed: ' . $e->getMessage());
}
catch( Exception $e) {

}
}
}

$handler = new Handler();
$handler->handleRequest($_POST);

这是获取 JSON 的 PHP 文件

<?php
// getr.php
require_once 'log.php';

class GetrHandler {
use Logger;

public function handleRequest($arg) {

try {
$this->log(__METHOD__);
$json = file_get_contents('data.json');
echo $json . "\n";
$this->log("output ". $json);
}
catch(PDOException $e) {
$this->log('Failed: ' . $e->getMessage());
}
catch( Exception $e) {

}
}
}

$handler = new GetrHandler();
$handler->handleRequest($_POST);

这是调试日志的代码

<?php
trait Logger {
function log($msg) {
file_put_contents('app.log', strftime('%Y-%m-%d %T ') . $msg . "\n", FILE_APPEND);
}
}

现在是 Swift 中的 ViewController 代码:

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func tapGet(sender: AnyObject) {

let URL: NSURL = NSURL(string: "http://*****.com/lab/getr.php")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "GET"

//request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);\
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in

if error != nil{
print("Error task -> \(error)")
return
}
else {

do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! [String]
print(result)
// for var i = 0; i<result.count; i++ {
// print("COUNT: \(i) \n \(result[i]) \n\n ")
// }
//completionHandler(strArray: result)
} catch {
print("Error -> \(error)")
}

}
}
task.resume()

}


@IBAction func tap(sender: AnyObject) {
let arr = [ "one", "two", "three" ]
let string = arrayToJSONBase64(arr)

print(string)

let URL: NSURL = NSURL(string: "http://******.com/lab/uploadr.php")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
let bodyData = "content=\(string)"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
print("appended data to body")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in

print("Sent request")
}
task.resume()

}

func arrayToJSONBase64(arr: [String]) -> String {
let data = try?NSJSONSerialization.dataWithJSONObject(arr, options: NSJSONWritingOptions(rawValue: 0))
let contentJsonBase64 = data!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

return contentJsonBase64
}

}

点击“Put”按钮后,这是我在服务器调试日志中得到的。

2016-03-16 13:17:50 Handler::handleRequest
2016-03-16 13:17:50 Array
(
[content] => WyJvbmUiLCJ0d28iLCJ0aHJlZSJd
)

2016-03-16 13:17:50 ["one","two","three"]

这是在 Xcode 日志中

["one", "two", "three"]
WyJvbmUiLCJ0d28iLCJ0aHJlZSJd
appended data to body
Sent request

点击“获取”按钮后:

服务器调试日志

2016-03-16 13:19:53 GetrHandler::handleRequest
2016-03-16 13:19:53 output ["one","two","three"]

代码:

["one", "two", "three"]

您现在可以在数据库中存储 $jsonContent。

关于php - mysql数据库中的Swift数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36017850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com