我正在尝试将 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/