Skip to content

Instantly share code, notes, and snippets.

@syky27
Last active February 14, 2018 13:01
Show Gist options
  • Save syky27/1aa9c3160bc197701622e810222fa965 to your computer and use it in GitHub Desktop.
Save syky27/1aa9c3160bc197701622e810222fa965 to your computer and use it in GitHub Desktop.
REALM Generic data fetch
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