0

I am sending String array(contains HTML code and names of images) to mysql with code:

    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()
}

I have to store it in mysql so I serialize this array and send to mysql(TEXT):

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

Finally I want to send it back to an iPhone so I request for it and send it from php:

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

Here is the code for 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()

}

And It returns an array with count 1. Looking like this:

COUNT: 0 ( &quot;&lt;!DOCTYPE html PUBLIC \&quot;-//W3C//DTD HTML 4.01//EN\&quot; \&quot;http://www.w3.org/TR/html4/strict.dtd\&quot;&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;meta http-equiv=\&quot;Content-Type\&quot; content=\&quot;text/html; charset=utf-8\&quot;&gt;\n&lt;meta http-equiv=\&quot;Content-Style-Type\&quot; content=\&quot;text/css\&quot;&gt;\n&lt;title&gt;&lt;/title&gt;\n&lt;meta name=\&quot;Generator\&quot; content=\&quot;Cocoa HTML Writer\&quot;&gt;\n&lt;style type=\&quot;text/css\&quot;&gt;\np.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 15.0px '.SF UI Text'; color: #ffffff}\nspan.s1 {font-family: 'Helvetica'; font-weight: normal; font-style: normal; font-size: 12.00pt; color: #000000}\nspan.s2 {font-family: '.SFUIText-Regular'; font-weight: normal; font-style: normal; font-size: 15.00pt; background-color: #555555}\nspan.s3 {font-family: '.SFUIText-Regular'; font-weight: normal; font-style: normal; font-size: 15.00pt; background-color: #969600}\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;p class=\&quot;p1\&quot;&gt;&lt;span class=\&quot;s1\&quot;&gt;aaaa&lt;/span&gt;&lt;span class=\&quot;s2\&quot;&gt;sadasdasdasdasdasd&lt;/span&gt;&lt;span class=\&quot;s3\&quot;&gt;asdasdasdasd&lt;/span&gt;&lt;/p&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n&quot;, &quot;&lt;imgnote&gt;474472.jpg&quot;, &quot;&lt;!DOCTYPE html PUBLIC \&quot;-//W3C//DTD HTML 4.01//EN\&quot; \&quot;http://www.w3.org/TR/html4/strict.dtd\&quot;&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;meta http-equiv=\&quot;Content-Type\&quot; content=\&quot;text/html; charset=utf-8\&quot;&gt;\n&lt;meta http-equiv=\&quot;Content-Style-Type\&quot; content=\&quot;text/css\&quot;&gt;\n&lt;title&gt;&lt;/title&gt;\n&lt;meta name=\&quot;Generator\&quot; content=\&quot;Cocoa HTML Writer\&quot;&gt;\n&lt;style type=\&quot;text/css\&quot;&gt;\np.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica}\nspan.s1 {font-family: 'Helvetica'; font-weight: normal; font-style: normal; font-size: 12.00pt}\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;p class=\&quot;p1\&quot;&gt;&lt;span class=\&quot;s1\&quot;&gt;&lt;/span&gt;&lt;/p&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n&quot; )

2
  • 2
    If "content" did not have JSON when you sent it to the server then it won't have JSON when you get it back. Commented Mar 15, 2016 at 17:22
  • I edited the question Commented Mar 16, 2016 at 14:17

2 Answers 2

2

In your Swift upload code:

  1. Take "content" and convert it to JSON
  2. Base64 encode the JSON
  3. Attach the Base64 encoded data to the request.

In 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);   

This is the PHP file to get back the JSON

<?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);   

Here is the code for debug log

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

And now the ViewController code in Swift:

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
    }

}

After tapping the "Put" button, this what I got in the server debug log.

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"]

This is in the Xcode log

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

After tapping the "Get" button:

Server debug log

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

Xcode:

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

You can now work on storing $jsonContent in your database.

Sign up to request clarification or add additional context in comments.

8 Comments

What does that mean? What are you getting back from the server? Is it JSON? Is that what you sent? What are you sending? Output what PHP receives. Dump out what is in the database. Log what the app gets when it asks for the data.
Thanks man! I have only one weird problem - my data.son looks strange. Here is the link to it: json
I did the same with an array ["one", "two", "three"] and it works. So it only has problems with sending array of strings containing HTML code.
ok. now we're getting somewhere. It's probably best to encode the html. You will have to decode it when it comes back down.
Will it be possible to decode it also in php? I'll need to use it on my website. How can I encode that?
|
0

First, log the value after each step. It is the easiest way to identify your problem.

Second, I see that Swift is doing UTF-8 encoding, but is it also doing URL-encoding?

Third, the value you retrieve from $_POST is already a string. That is, $content is a string, ... so why are you serializing it? It's already serialized. Thus, you also don't need to unserialize it.

Fourth, you're interpreting the returned content as JSON, but there is no indication the content you send initially is in JSON format.

Lastly, you describe your data as an array several times, but I don't see any arrays.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.