SoFunction
Updated on 2025-04-08

Using JSONModel instance code in Swift

Preface

First of all, all models should be written using OC - do you want to close the web page after seeing this sentence - - #, I wrote directly in swift and kept reporting errors, so I wrote using OC. Here I mainly share my experience with Alamofire.

text

The two projects JSONModel and Alamofire are not discussed here, just apply the code.

#import ""

@interface BaseModel : JSONModel

-(instancetype)initWithDictionary:(NSDictionary*)dict;

@end


#import ""

@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

All Models must inherit BaseModel, and other writing methods are the same

  

internal func requestModel<T: BaseModel>(method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, success: (T) -> Void, failure: (NSError?) -> Void) {
    (method, URLString , parameters: parameters, encoding: )
      .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) {
    (method, URLString , parameters: parameters, encoding: )
      .responseJSON { (request, response, data, error) in
        if error == nil {
          if let array = data as? NSArray {
            if let result = (array as [AnyObject]).copy() as? Array<T>{
              success(result)
              return
            }
          }
        }
        failure(error)
    }
  }

Code description

1. mHttpManager is Alamofire Manager object

2. Pay attention to the data format returned by the server. Model and Array<Model> are supported here.

3. Note that in Swift, NSDictionary is converted to Model, use T (dictionary: dict as [NSObject: AnyObject]), this T is the specific generic type

4. Pay attention to converting NSArray to Model array in Swift, use (array as [AnyObject]).copy() as? Array<T>, be careful not to use BaseModel. arrayOfModelsFromDictionaries (the compiler will not report an error but the type will not be transferred out)

5. Specific usage:

 public func casts(success: (Array<CustomModel>) -> Void, failure: (NSError?) -> Void) {
        requestArray(, URL_CASTS, parameters: nil, success: success, failure: failure)
      }
      
      public func like(id: String, success: (CustomModel) -> Void, failure: (NSError?) -> Void) {
        requestModel(, String(format: URL_CASTS_LIKE, id), parameters: nil, success: success, failure: failure)
      }

The above is the example code of using JSONModel in Swift. Friends who need it can refer to it.