Ich versuche eine Post-Anfrage mit Kopfzeilen mit Alamofire in Swift zu stellen. Ich bekomme jedoch immer den Parameter extra im Methodenaufruf error. Ich verwende Version 4.5 von Alamofire. Ich kann den Fehler nicht herausfinden.
Den Code finden Sie im Anhang
let headers = ["Authorization": token, "Content-Type": "application/json"]
Alamofire.request("http://localhost:8000/create", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
}
Fügen Sie auf diese Weise Header hinzu
let headers = ["Authorization" : "Bearer "+accessToken!+"",
"Content-Type": "application/json"]
Alamofire.request(URL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON
{ (response:DataResponse) in
switch(response.result)
{
case .success(let value):
// zur Json-Serialisierung hinzufügen
let JSON = try JSONSerialization.jsonObject(with: response.data! as Data, options:JSONSerialization.ReadingOptions(rawValue: 0))
guard let JSONDictionary: NSDictionary = JSON as? NSDictionary else {
return
}
completionHandler(JSONDictionary as? NSDictionary, nil)
case .failure(let error):
completionHandler(nil, error as NSError?)
break
}
}
Ich habe wie unten verwendet und es funktioniert für mich: -
if let url = URL(string: "http://localhost:8000/create") {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.post.rawValue
urlRequest.addValue(token, forHTTPHeaderField: "Authorization")
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(urlRequest)
.responseJSON { response in
self.parseData(response.data!)
}
}
func parseData(_ data : Data){
do{
let readableJSON = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String :AnyObject]
print("readableJSON : \(readableJSON)")
}
catch{
print(error)
}
}
func postRequestForAPI(apiType : WSRequestType, parameters : NSDictionary? = nil, completionHandler:@escaping (_ responseObject : NSDictionary?, _ error : NSError?) -> Void)
{
if !WSClient.sharedInstance.isConnectedToNetwork(){
CommonUnit.ProgressHud(progressState: ProgressHud_State.StopAnimation)
CommonUnit.alertController("Network Error", message: "Internet Connection not Available!", okTitle: "Ok", okCompletion: {
})
return
}
let apipath : String = getAPI(apiType: apiType)
var apiParams : NSDictionary!
print(parameters ?? "")
if (parameters != nil)
{
apiParams = convertDictToJson(dict: parameters!)
}
print("API : \(apipath)")
if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
appVersion = version
}
if CommonUnit.isUserAlreadyLogIn() {
Constant.Common.headerToken = UserDefaults.standard.value(forKey: Constant.UserDefaultKey.headerToken) as! String
}
let headers: HTTPHeaders = [
"header_token": Constant.Common.headerToken,
"device_type": "1",
"device_token": Constant.Common.DeviceToken,
"app_version": appVersion!,
"app_type":"1",
"Accept": "application/json"
]
print("headers = \(headers)")
print(apiParams)
Alamofire.request(apipath, method: .post, parameters: apiParams as? Parameters, encoding: URLEncoding.default, headers: headers)
.responseJSON { response in
switch(response.result) {
case .success(_):
do {
let JSON = try JSONSerialization.jsonObject(with: response.data! as Data, options:JSONSerialization.ReadingOptions(rawValue: 0))
print(JSON)
guard let JSONDictionary: NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
return
}
let badge_count = String(CommonUnit.checkIfNull(someObject: JSONDictionary[Constant.dictKey.badge_count] as AnyObject))
if badge_count == nil || badge_count == "0" {
CommonUnit.btnNotification.badgeString = "0"
UIApplication.shared.applicationIconBadgeNumber = 0
}else{
CommonUnit.btnNotification.badgeString = badge_count
if (badge_count?.isEmptyString())! == false && CommonUnit.isUserAlreadyLogIn(){
UIApplication.shared.applicationIconBadgeNumber = Int(badge_count!)!
}
}
completionHandler(JSONDictionary, nil)
}
catch let JSONError as NSError {
print("\(JSONError)")
CommonUnit.ProgressHud(progressState: ProgressHud_State.StopAnimation)
}
break
case .failure(_):
CommonUnit.ProgressHud(progressState: ProgressHud_State.StopAnimation)
CommonUnit.alertController((response.result.error?.localizedDescription as NSString?)!, message: "", okTitle: "OK", okCompletion: nil)
print(response.result.error?.localizedDescription as NSString!)
break
}
}
}