[英]Working with Alamofire
與Alamofire合作,獲得:
Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(錯誤域= NSCocoaErrorDomain代碼= 3840“字符2周圍的值無效。”錯誤
這是我在NetworkClass
代碼:
class func requestPOSTURL(_ strURL : String, params :[String:String], success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void){
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON { (responseObject) -> Void in
print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
並要求致電:
let strURL = "myurl"
let parameters : [String: String] =
[
"user_name":"SNSH" as String,
"password":"SNOSH" as String,
"device_id":"0D4F5322-81C0-0000-9210-70DA0C6BC04C" as String,
]
if let json = try? JSONSerialization.data(withJSONObject: parameters, options: []) {
// here `json` is your JSON data, an array containing the String
// if you need a JSON string instead of data, then do this:
if let content = String(data: json, encoding: String.Encoding.utf8) {
// here `content` is the JSON data decoded as a String
print(content)
print(parameters)
NetworkClass.requestPOSTURL(strURL, params: parameters, success: {
(JSONResponse) -> Void in
print(JSONResponse)
}) {
(error) -> Void in
print(error)
}
}
}
我需要在參數中發送字符串。
let urlAsString1 : String = API
let urlStr : NSString = urlAsString1.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let params:NSMutableDictionary? = [
"user_name":"SNSH" as String,
"password":"SNOSH" as String,
"device_id":"0D4F5322-81C0-0000-9210-70DA0C6BC04C" as String,
];
let ulr = NSURL(string:urlStr as String)
let request = NSMutableURLRequest(URL: ulr!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data = try! NSJSONSerialization.dataWithJSONObject(params!, options: NSJSONWritingOptions.PrettyPrinted)
let json = NSString(data: data, encoding: NSUTF8StringEncoding)
if let json = json {
print(json)
}
request.HTTPBody = json!.dataUsingEncoding(NSUTF8StringEncoding);
Alamofire.request(request)
.responseJSON { response in
// do whatever you want here
switch (response.result) {
case .Success(let JSON):
print("JSON: \(JSON)")
let responseString = JSON as! NSDictionary
print(responseString)
break;
case .Failure:
break
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.