dongqu9972 2016-03-17 22:14
浏览 58

在Swift中通过JSON发送HTML代码

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:

MY OUTPUT

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统