我正在尝试从PHP发送JSON到iOS Swift。
但是当我在Swift中解码json时,值是",
虽然钥匙出来很好。
我知道PHP中的变量必须是UTF-8编码的,但即使在编码之后也会出现同样的问题。
谁能帮我解决这个问题?
你可以直接复制&粘贴PHP和Swift代码。
如果我在web浏览器中运行这段代码,我得到
{"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);