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

Posted

技术标签:

【中文标题】在 Swift iOS 中解码的 PHP JSON 返回空值【英文标题】:PHP JSON decoded in Swift iOS returns empty value 【发布时间】:2015-07-09 17:41:59 【问题描述】:

我正在尝试将 JSON 从 php 发送到 ios Swift。

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

虽然钥匙出来的很好。

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

谁能帮我解决这个问题?

您可以复制粘贴 PHP 和 Swift 代码。


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

"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 = "";
)

【问题讨论】:

显示收到的数据:println( NSString(data: data, encoding: NSUTF8StringEncoding) ) 您还没有检查 NSError 值是什么,您应该始终将其作为第一步 错误显示为零。和 println( NSString(data: data, encoding: NSUTF8StringEncoding) ) 返回 'Optional("upDirection":"")' 【参考方案1】:

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

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 返回空值的主要内容,如果未能解决你的问题,请参考以下文章

在 swift 4 和 Xcode 9 中解码 ExpandableTableView 的嵌套 json 数组

如何在 swift 4.1 和 xcode 9.3 中使用 JSONDecoder 解码嵌套的 JSON 数组和对象?

如何在 Swift 4 中为 JSON 编写可解码,其中键是动态的?

Apollo graphQL:在 iOS swift 中使用自定义标量时解码数组时出错

使用 Alamofire 将 JSON 解码为对象

在 Swift 中解码任意 JSON