尝试发布数据时遇到此错误:“由于格式不正确,无法读取数据”
class ViewController: UIViewController {
@IBOutlet weak var recipe_id: UITextField!
var getdata = NSMutableData()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func Btn_Sav(_ sender: Any)
{
let url_str = URL(string:"http://iroidtechnologies.in/bigfish/Bigfish_cntrl/HealthyFish_Recipes_Detail")
var url_req = URLRequest(url: url_str!)
url_req.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "context_type")
url_req.httpMethod = "Post"
let Poststring = "recipe_id=\(recipe_id.text))"
url_req.httpBody = Poststring.data(using: .utf8)
let task = URLSession.shared.dataTask(with: url_req){(data,request,error) in
if let mydata_post = data
{
self.getdata.append(mydata_post)
do
{
let jsondata_post = try JSONSerialization.jsonObject(with: self.getdata as Data, options: []) as! NSDictionary
print("jsondata_post------->",jsondata_post)
}
catch{
print("error",error.localizedDescription)
}
}
};
task.resume()
}
尝试发布数据时遇到此错误:“由于格式不正确,无法读取数据”
答案 0 :(得分:0)
最可能的问题是可选的text
属性,该属性将文字Optional(
添加到字符串中,而结尾的)
也可能不是故意的。
您必须解开可选内容(请命名变量 lowerCamelCased )。
let postString = "recipe_id=\(recipe_id.text!)"
和httpMethod
字符串应该大写
urlReq.httpMethod = "POST"
进一步删除getdata
var getdata = NSMutableData()
不需要它,无论如何您都不应该在Swift中使用NSMutableData
。并使用本机Swift集合类型,而不要使用NSDictionary
和NSArray
if let data = data {
do {
let jsondataPost = try JSONSerialization.jsonObject(with: data) as! [String:Any]
...