问题
I am new to swift. And I am working on swift project. I have getting response from server response like follows
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 {
In above code, I am checking multiple times whether its dictionary or not, or assign as dictionary. I am doing this kind exercise in all my classes. So, I want to create some modal class for common logic, And I want to use that logic every class after getting Webservice data.
And my response from webservice is follows
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;
};
And I am using Alamofire for API calls.
Can anyone help me here, to achieve this? Thanks!
回答1:
Since you are using Alamofire in your kNetworkManager
, I would suggest to also use AlamofireObjectMapper to get rid of the hassle of parsing the response and mapping it into a model:
An extension to Alamofire which automatically converts JSON response data into swift objects using ObjectMapper.
It is easy to be integrated, you could check its documentation to get familiar of how you could do it.
Based on the response you mentioned, the mappable object should similar to:
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"]
}
}
Also, if you are using Swift 4, you might want to take a look at Codable, it should make your life easier!
回答2:
If you using Alamofire then. Use this Common method
//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)
}
}
Please adjust this Methods according to you because i am directly copy this methods in my network common class
来源:https://stackoverflow.com/questions/47919964/how-to-create-model-class-for-json-response-from-webservice-in-swift-3