编码日期格式时出错,以便在swift3中的json中使用它

时间:2017-07-18 06:53:48

标签: json swift3

let dateFormatter1 : DateFormatter = DateFormatter()
dateFormatter1.dateFormat = "dd/MMM/yyyy HH:mm:ss"

let date1 = Date()
let myString1 = dateFormatter1.string(from: date1)

let data1 = myString1.data(using: .utf8)

self.dateString1 = String(data: data1!, encoding: .utf8)!

func postYumms() {
    let delegate = UIApplication.shared.delegate as? AppDelegate

    if let context = delegate?.persistentContainer.viewContext{
       let person = NSEntityDescription.insertNewObject(forEntityName: "Mydata", into: context) as! Mydata
       let newString = self.timeString.replacingOccurrences(of: "", with: "/")
       let dateescapedString = self.dateString.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)
       let timeescapedString = newString.addingPercentEncoding(withAllowedCharacters:.urlQueryAllowed)
       print(timeescapedString!)

       let joinString = dateescapedString! + "+" + newString

       let parameters = "Post_id=\(self.ID)" + "&Post_type=\(self.PTYPE)" + "&Created_by=\(self.UID)" + "&Created_on=\(self.dateString1)"
       print(parameters)

       let url = "http://shiftu.org/api/zTimeline/post_like?"

       let upara = url + parameters

       print(upara)

       Alamofire.request(upara, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
           switch(response.result) {
           case .success(_):
               if response.result.value != nil{
                   print(response.result.value!)
               }
               break

           case .failure(_):
               print(response.result.error!)
               break
           }
    }
}

显示错误,如

invalidURL("http://shiftu.org/api/zTimeline/post_like?Post_id=8172&Post_type=1&Created_by=3234&Created_on=18/Jul/2017 12:14:02"

拜托,有人帮助我

1 个答案:

答案 0 :(得分:0)

问题是您使用带有空格的日期的字符串表示作为URL查询参数,而不对URL进行编码。 你实际上是编码,但是不要在任何地方使用编码的字符串。

只需更改此行即可解决您的问题:

let parameters = "Post_id=\(self.ID)" + "&Post_type=\(self.PTYPE)" + "&Created_by=\(self.UID)" + "&Created_on=\(joinString)"