我正在尝试使用 Alamofire 和 body 来执行发布请求:
let credential = URLCredential(user: appDelegate.username!, password: appDelegate.password!, persistence: .none)
var url = URL(string: webservice)
var request = URLRequest(url: url!)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
request.httpBody = jsonData
let urlRequest: Alamofire.URLRequestConvertible = request
AF.request(urlRequest as! URLConvertible, headers: headers).authenticate(with: credential).response { response in
}
但我收到这些错误:
当我执行实际请求时,无法将“Foundation.URLRequest”类型的值转换为“Alamofire.URLConvertible”。如何将 Foundation.URLRequest 转换为 Alamofire.URLConvertible?
谢谢,
要清理 jsonData 是什么:
let jsonData: Data? = try? JSONSerialization.data(withJSONObject: jsonArrayOfDictionaries, options: .prettyPrinted)
而 jsonArrayOfDictionaries 是:
var jsonArrayOfDictionaries = [[AnyHashable: Any]]()
它的填充方式如下:
for i in 0..<cellHolder.count {
//Define Dictionary for grading data
var jsonDict = [AnyHashable: Any]()
jsonDict["ID"] = cellHolder[i].id
jsonDict["item"] = cellHolder[i].item
jsonDict["Notes"] = cellHolder[i].notes
jsonArrayOfDictionaries.append(jsonDict)
jsonDict = [AnyHashable: Any]()
}
cellHolder 是我创建的类的数组
class MyClass: NSObject {
var id: Int?
var item: String?
var notes: String?
init(id: Int?, item: String?, notes: Int?) {
super.init()
self.id = id
self.item = item
self.notes = notes
}
}
删除标头并让请求正常工作:
let credential = URLCredential(user: appDelegate.username!, password: appDelegate.password!, persistence: .none)
var url = URL(string: webservice)
var request = URLRequest(url: url!)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
request.httpBody = jsonData
AF.request(request).authenticate(with: credential).response { response in
}