Last active
February 14, 2018 13:01
-
-
Save syky27/1aa9c3160bc197701622e810222fa965 to your computer and use it in GitHub Desktop.
REALM Generic data fetch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol APIProtocol { | |
init(_ j: [String: Any]) | |
} | |
extension APIWrapper { | |
func getAllObjectsOf<T: APIProtocol>(type: T.Type, request: URLRequestConvertible, _ completion: @escaping (_ result: (T.Type, ResultState)) -> Void) { | |
Alamofire.request(request).validate().response { response in | |
do { | |
if let data = response.data { | |
let objs : [[String: Any]] = try JSONSerialization.jsonObject(with: data, options: []) as! [[String:Any]] | |
let realm = try Realm() | |
realm.beginWrite() | |
objs.forEach({ objectJSON in | |
let object = type.init(objectJSON) | |
realm.add(object as! Object, update: true) | |
}) | |
try realm.commitWrite() | |
completion((type, ResultState.success)) | |
} else { | |
completion((type, ResultState.failure(APIError(code: "I-1", message: "API did not return data")))) | |
} | |
}catch(let e) { | |
completion((type, ResultState.failure(APIError(code: "I-2", message: e.localizedDescription)))) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment