I have to send NSAttributedString
to mysql and be able to edit in on my website. I thought that the best idea will be converting NSAttributedString
into array of Strings. But I have a problem with sending it. Firstly code(done thanks to one user of stack overflow:)):
func uploadNote(user: String, title: String, category: String, content: [String]) {
let URL: NSURL = NSURL(string: "http://site/uploadNote.php")!
let string = arrayToJSONBase64(content)
print(string)
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: .PrettyPrinted)
let contentJsonBase64 = data!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
return contentJsonBase64
}
And 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);
log.php:
<?php
trait Logger {
function log($msg) {
file_put_contents('app.log', strftime('%Y-%m-%d %T ') . $msg . "
", FILE_APPEND);
}
}
The problem is that when I send an array like ["one", "two", "three"]
everything is ok, it's saved in data.json
and everything is all right. But when I try to send HTML code my data.json
looks like this: