Domain=NSCocoaErrorDomain Code=3840について
swift3.0でJSONを解析したいのですが下記のエラーが出てしまい困っています。
swift、PHPともに勉強中ですのでまだ理解してない部分も多いです。
このような説明で大変申し訳ないのですが、ご教示お願いいたします。
Error 43-> Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
以下ソースコードになります。
.swift
let array = ["data=文字列"]
do {
let jsonData = try JSONSerialization.data(withJSONObject: array, options: .prettyPrinted)
let request = NSMutableURLRequest(url: NSURL(string: "http://localhost/test.php")! as URL)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
if error != nil{
print("Error 55 -> \(error)")
return
}
do {
let result = try JSONSerialization.jsonObject(with: data!)
print("Result 34 -> \(result)")
} catch {
print("Error 43-> \(error)")
}
}
task.resume()
}
catch {
print(error)
}
.php
$json = $_POST['data'];
header('Content-type: application/json');
echo json_encode($json);