我是Swift的新手。我正在从事Swift项目。我得到了服务器响应的响应,如以下内容
kNetworkManager.executePostRequest(urlString: kAppSocialLoginURL, params:mainDictionary, requestVC: self,completionHandler: {(responseObject) -> () in
// print("response object:(responseObject!)")
if responseObject != nil {
let responseDictionary = responseObject as! NSDictionary
if responseDictionary is NSDictionary{
let obj = responseDictionary.value(forKey:"user")
if obj is NSDictionary{ //success case
print("NSDictionary is",obj ?? NSDictionary())
UtilityClass.sharedInstance.userDetailsDictionary = responseDictionary as! [String : AnyObject]
if let obj = responseDictionary.value(forKey:"user") as? NSDictionary {
if let sessionId = obj["token"] as? String {
UtilityClass.sharedInstance.kSessionIDString = sessionId
}
if let userObj = obj["user"] as? NSDictionary {
在上面的代码中,我多次检查其字典,还是分配为字典。我在所有课程中都在做这种练习。因此,我想为常见逻辑创建一些模态类,并且我想在获取WebService数据后使用该逻辑。
我对Web服务的回答如下
user = {
sessid = "-qadadadad";
"session_name" =aadadad;
tokenData = adadadad;
user = {
access = 1513647;
created = 14822;
data = {
"ckeditor_auto_lang" = t;
"ckeditor_default" = t;
"ckeditor_lang" = en;
"ckeditor_show_toggle" = t;
"ckeditor_width" = "100%";
contact = 1;
};
我正在使用Alamofire进行API调用。
谁能在这里帮助我,实现这一目标?谢谢!
由于您在kNetworkManager
中使用了Alamofire,我建议还使用AlamofireObjectMapper来摆脱解析响应的麻烦并将其映射到模型中:
Alamofire的扩展,该扩展自动转换JSON响应 使用ObjectMapper将数据数据数据。
很容易集成,您可以检查其文档以熟悉如何做。
根据您提到的响应,映射对象应与:
相似。import ObjectMapper
class UserResponse: Mappable {
var sessId: String?
var sessionName: String?
var tokenData: String?
var user: User?
required init?(map: Map) {
}
func mapping(map: Map) {
sessId <- map["sessid"]
sessionNamen <- map["session_name"]
tokenData <- map["tokenData"]
user <- map["user"]
}
}
class User: Mappable {
var access: Int?
var created: Int?
required init?(map: Map){
}
func mapping(map: Map) {
access <- map["day"]
created <- map["access"]
conditions <- map["created"]
data <- map["data"]
}
}
class UserData: Mappable {
var ckEditorAutoLang: String?
var ckEditorDefault: String?
var ckEditorLang: String?
var ckEditorShowToggle: String?
var ckEditorWidth: String?
var contact: Int?
required init?(map: Map){
}
func mapping(map: Map) {
ckEditorAutoLang <- map["ckeditor_auto_lang"]
ckEditorDefault <- map["ckeditor_default"]
ckEditorLang <- map["ckeditor_lang"]
ckEditorShowToggle <- map["ckeditor_show_toggle"]
ckEditorWidth <- map["ckeditor_width"]
contact <- map["contact"]
}
}
另外,如果您使用的是Swift 4,您可能想看看Codable
,它应该使您的生活更轻松!
如果您使用Alamofire。使用这种常见方法
//MARK:- Public Method
/**
* Initiates HTTPS or HTTP request over |kHTTPMethod| method and
returns call back in success and failure block.
*
* @param serviceName name of the service
* @param method method type like Get and Post
* @param postData parameters
* @param responeBlock call back in block
*/
func requestApi(serviceName: String, method: kHTTPMethod, postData: Dictionary<String, Any>, withProgressHUD showProgress: Bool, completionClosure:@escaping (_ result: Any?, _ error: Error?, _ errorType: ErrorType, _ statusCode: NSNumber?) -> ()) -> Void
{
if NetworkReachabilityManager()?.isReachable == true
{
if showProgress
{
showProgressHUD()
}
let headers = getHeaderWithAPIName(serviceName: serviceName)
let serviceUrl = getServiceUrl(string: serviceName)
let params = getPrintableParamsFromJson(postData: postData)
print_debug(items: "Connecting to Host with URL (kBASEURL)(serviceName) with parameters: (params)")
print_debug(items: "###### (postData) ######")
//NSAssert Statements
assert(method != .GET || method != .POST, "kHTTPMethod should be one of kHTTPMethodGET|kHTTPMethodPOST|kHTTPMethodPOSTMultiPart.");
switch method
{
case .GET:
Alamofire.request(serviceUrl, method: .get, parameters: postData, encoding: URLEncoding.default, headers: headers).responseJSON(completionHandler:
{ (DataResponse) in
SVProgressHUD.dismiss()
switch DataResponse.result
{
case .success(let JSON):
print_debug_fake(items: "Success with JSON: (JSON)")
print_debug(items: "Success with status Code: (String(describing: DataResponse.response?.statusCode))")
let response = self.getResponseDataDictionaryFromData(data: DataResponse.data!)
completionClosure(response.responseData, response.error, .requestSuccess, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
case .failure(let error):
print_debug(items: "json error: (error.localizedDescription)")
if error.localizedDescription == "cancelled"
{
completionClosure(nil, error, .requestCancelled, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
}
else
{
completionClosure(nil, error, .requestFailed, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
}
}
})
case .POST:
Alamofire.request(serviceUrl, method: .post, parameters: postData, encoding: JSONEncoding.default, headers: headers).responseJSON(completionHandler:
{ (DataResponse) in
SVProgressHUD.dismiss()
switch DataResponse.result
{
case .success(let JSON):
print_debug_fake(items: "Success with JSON: (JSON)")
print_debug(items: "Success with status Code: (String(describing: DataResponse.response?.statusCode))")
let response = self.getResponseDataDictionaryFromData(data: DataResponse.data!)
completionClosure(response.responseData, response.error, .requestSuccess, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
case .failure(let error):
print_debug(items: "json error: (error.localizedDescription)")
completionClosure(nil, error, .requestFailed, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
}
})
case .PUT:
Alamofire.request(serviceUrl, method: .put, parameters: postData, encoding: JSONEncoding.default, headers: headers).responseJSON(completionHandler:
{ (DataResponse) in
SVProgressHUD.dismiss()
switch DataResponse.result
{
case .success(let JSON):
print_debug_fake(items: "Success with JSON: (JSON)")
print_debug(items: "Success with status Code: (String(describing: DataResponse.response?.statusCode))")
let response = self.getResponseDataDictionaryFromData(data: DataResponse.data!)
completionClosure(response.responseData, response.error, .requestSuccess, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
case .failure(let error):
print_debug(items: "json error: (error.localizedDescription)")
completionClosure(nil, error, .requestFailed, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
}
})
case .PATCH:
Alamofire.request(serviceUrl, method: .patch, parameters: postData, encoding: JSONEncoding.default, headers: headers).responseJSON(completionHandler:
{ (DataResponse) in
SVProgressHUD.dismiss()
switch DataResponse.result
{
case .success(let JSON):
print_debug_fake(items: "Success with JSON: (JSON)")
print_debug(items: "Success with status Code: (String(describing: DataResponse.response?.statusCode))")
let response = self.getResponseDataDictionaryFromData(data: DataResponse.data!)
completionClosure(response.responseData, response.error, .requestSuccess, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
case .failure(let error):
print_debug(items: "json error: (error.localizedDescription)")
completionClosure(nil, error, .requestFailed, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
}
})
case .DELETE:
Alamofire.request(serviceUrl, method: .delete, parameters: postData, encoding: URLEncoding.default, headers: headers).responseJSON(completionHandler:
{ (DataResponse) in
SVProgressHUD.dismiss()
switch DataResponse.result
{
case .success(let JSON):
print_debug_fake(items: "Success with JSON: (JSON)")
print_debug(items: "Success with status Code: (String(describing: DataResponse.response?.statusCode))")
let response = self.getResponseDataDictionaryFromData(data: DataResponse.data!)
completionClosure(response.responseData, response.error, .requestSuccess, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
case .failure(let error):
print_debug(items: "json error: (error.localizedDescription)")
completionClosure(nil, error, .requestFailed, NSNumber.getNSNumber(message: DataResponse.response?.statusCode))
}
})
}
}
else
{
SVProgressHUD.dismiss()
completionClosure(nil, nil, .noNetwork, nil)
}
}
请根据您调整此方法,因为我直接在网络公共类中复制此方法