Created
June 12, 2016 21:34
-
-
Save victoraugustolls/a162ad1cacac611ddf0cb9ed5a9ebd85 to your computer and use it in GitHub Desktop.
Example of fetching Mapped Object using Realm and Alamofire
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
import UIKit | |
import ObjectMapper | |
import RealmSwift | |
class Example: Object, Mappable, Meta { | |
dynamic var id: Int = 0 | |
dynamic var title: String = "" | |
dynamic var author: String = "" | |
dynamic var genre: String = "" | |
//Realm | |
override static func primaryKey() -> String? { | |
return "id" | |
} | |
//Object Mapper | |
required convenience init?(_ map: Map) { | |
self.init() | |
} | |
func mapping(map: Map) { | |
id <- map["id"] | |
title <- map["title"] | |
author <- map["author"] | |
genre <- map["genre"] | |
} | |
//Meta | |
static func url() -> String { | |
return "https://demo7589466.mockable.io/books" | |
} | |
} |
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
import Foundation | |
import Alamofire | |
import AlamofireObjectMapper | |
import RealmSwift | |
import ObjectMapper | |
class FetchData { | |
typealias SuccessCallback = () -> Void | |
typealias FailCallback = (NSError) -> Void | |
static func fetchSomeData <T:Object where T:Mappable,T:Meta> (type:T.Type, success: SuccessCallback, fail: FailCallback) { | |
Alamofire.request(Method.GET, type.url()) | |
.responseArray { (response: Response<[T], NSError>) in | |
switch response.result { | |
case .Success(let items): | |
autoreleasepool{ | |
do { | |
let realm = try Realm() | |
try realm.write { | |
for item in items { | |
realm.add(item, update: true) | |
} | |
} | |
} catch let error as NSError { | |
fail(error) | |
} | |
} | |
success() | |
case .Failure(let error): | |
fail(error) | |
break | |
} | |
} | |
} | |
} |
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 Meta { | |
static func url() -> String | |
} |
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
FetchData.doSomeWork(Books.self, success: { | |
print("success") | |
}, fail: { (error) in | |
print(error) | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment