媒介
起首一切的Model照樣應用oc來寫——看到這一句是否是想關網頁了- - #,在swift外面直接寫一向報錯所以就遷就用oc來寫了,這裡重要是分享一下搭配Alamofire應用的經歷。
注釋
這裡不評論辯論JSONModel和Alamofire這兩個項目,直接上代碼,BaseModel.h
#import "JSONModel.h" @interface BaseModel : JSONModel -(instancetype)initWithDictionary:(NSDictionary*)dict; @end
BaseModel.m
#import "BaseModel.h" @implementation BaseModel //Make all model properties optional (avoid if possible) +(BOOL)propertyIsOptional:(NSString*)propertyName { return YES; } -(instancetype)initWithDictionary:(NSDictionary*)dict { return (self = [[super init] initWithDictionary:dict error:nil]); } @end
一切的Model都要繼續BaseModel,其他寫法都一樣
BaseAPI.swift
internal func requestModel<T: BaseModel>(method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, success: (T) -> Void, failure: (NSError?) -> Void) { mHttpManager.request(method, URLString , parameters: parameters, encoding: ParameterEncoding.JSON) .responseJSON { (request, response, data, error) in if error == nil { if let dict = data as? NSDictionary { if let model = T(dictionary: dict as [NSObject : AnyObject]) { success(model) return } } } failure(error) } } internal func requestArray<T: BaseModel>(method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, success: (Array<T>) -> Void, failure: (NSError?) -> Void) { mHttpManager.request(method, URLString , parameters: parameters, encoding: ParameterEncoding.JSON) .responseJSON { (request, response, data, error) in if error == nil { if let array = data as? NSArray { if let result = T.arrayOfModelsFromDictionaries(array as [AnyObject]).copy() as? Array<T>{ success(result) return } } } failure(error) } }
代碼解釋
1、mHttpManager這個是Alamofire的Manager對象
2、留意辦事真個前往的數據格局,這裡支撐Model和Array<Model>
3、留意在Swift外面NSDictionary轉Model,用T(dictionary: dict as [NSObject : AnyObject]),這個T就是詳細的泛型類型
4、留意在Swift外面NSArray轉Model數組,用T.arrayOfModelsFromDictionaries(array as [AnyObject]).copy() as? Array<T>,留意不要用BaseModel. arrayOfModelsFromDictionaries(編譯不會報錯然則類型轉不出來)
5、詳細用法:
public func casts(success: (Array<CustomModel>) -> Void, failure: (NSError?) -> Void) { requestArray(Method.GET, URL_CASTS, parameters: nil, success: success, failure: failure) } public func like(id: String, success: (CustomModel) -> Void, failure: (NSError?) -> Void) { requestModel(Method.PATCH, String(format: URL_CASTS_LIKE, id), parameters: nil, success: success, failure: failure) }
以上就是在Swift中應用JSONModel 實例代碼,有須要的同伙可以參考下。
【在Swift中應用JSONModel 實例代碼】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!