在 Swift iOS 中解码 PHP JSON 返回空值

标签 php ios json swift

我正在尝试将 JSON 从 PHP 发送到 iOS Swift。

但是当我在 Swift 中解码 json 时,值为“”,

虽然 key 出来得很好。

我了解到 PHP 中的变量必须采用 UTF-8 编码,但即使在编码后也会出现同样的问题。

谁能帮我解决这个问题吗?

您只需复制并粘贴 PHP 和 Swift 代码即可。

<小时/>

如果我在网络浏览器中运行此代码,我会得到

{"upDirection":"\u00ec\u00a2\u0085\u00ed\u0095\u00a9\u00ec\u009a\u00b4\u00eb\u008f\u0099\u00ec\u009e\u00a5"}

这是代码:

<?php
//if(isset($_POST["stationId"]) && isset($_POST["dateTime"])) {
   include('simple_html_dom.php');

   /* for testing */
   $station_id = "923";
   $date_time  = "201507091750";

   $url  = "http://m.map.naver.com/pubtrans/inquireSubwayDepartureInfo.nhn?stationID=".$station_id."&inquiryDateTime=".$date_time."00&count=5&caller=mobile_naver_map&output=json";
   $html = file_get_contents($url);


    //Json to array
    $json   = json_decode($html, true);
    $result = $json["result"];


    /**
    upDirection
    **/
    $upDirection   = $result["upDirection"];
    $upDirection   = utf8_encode($upDirection);


    // Return as json
    $return_json = [
        "upDirection" => $upDirection
    ];


    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($return_json);
//}
?>

这是 swift 中的代码

func fetchTimeSchedule() {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
        // Send the station ID to PHP
        var url: NSURL = NSURL(string: self.timeScheduleUrl)!
        var request:NSMutableURLRequest = NSMutableURLRequest(URL:url)

        // Prepare post data
        // station id
        let stationId = self.currentViewingStation.id

        // datetime
        let date       = NSDate()
        let calendar   = NSCalendar.currentCalendar()
        let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay |  .CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
        let year       = components.year
        let month      = components.month  < 10 ? "0\(components.month)"  : "\(components.month)"
        let day        = components.day    < 10 ? "0\(components.day)"    : "\(components.day)"
        let hour       = components.hour   < 10 ? "0\(components.hour)"   : "\(components.hour)"
        let minutes    = components.minute < 10 ? "0\(components.minute)" : "\(components.minute)"
        let dateTime = "\(year)\(month)\(day)\(hour)\(minutes)"

        var bodyData = "stationId=\(stationId)&dateTime=\(dateTime)"

        request.HTTPMethod = "POST"
        request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
        println("bodyData:\(bodyData)")

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            if error != nil {
                println("error = \(error)")
                return
            }

            if let HTTPresponse = response as? NSHTTPURLResponse {
                println("received:\(HTTPresponse.statusCode)")
                if HTTPresponse.statusCode == 200 { // Successfully got response
                    var err: NSError?
                    if let json : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err)  {
                        // decode json
                        println(json) // <- Here ******************
                    }
                }
            }
        }
        task.resume()
    })
}

这就是该行

println(json) // <- Here ****************** 

打印输出:

Optional({
    upDirection = "";
})

最佳答案

我用这段代码解决了这个问题:

let url = NSURL(string:yourUrl)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"

// set Content-Type in HTTP header
let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)

// set data
var dataString = "user=mike"
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData

var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)

let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
println("API Response: \(results)")

使用这个 php

header('Content-Type: application/json; charset=utf-8');
$a1 = $_POST['user'];
$returnValue = array("a1"=>$a1);
echo json_encode($returnValue);

关于在 Swift iOS 中解码 PHP JSON 返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31324617/

相关文章:

php - PDO UPDATE 似乎不存储引号?

javascript - 谷歌浏览器扩展内容安全政策

javascript - 如果 JSON 响应上的图像 src 为空如何设置默认本地镜像

java - 将 JSON 转换为 CSV

php - 如何显示受 http 身份验证保护的图像

php - MYSQL 查询在使用 where、group by 和 order by 时花费太多时间

php - 如何评估算术微积分?

ios - 如何将接收方的 ACCEPT 和 DECLINE 操作通知发送方?

iphone - 如何获得认证玩家的高分表格排行榜(游戏中心)

ios - Estimote Ibeacon 无法在 Mac 上检测到 2011 年底