Last active
October 1, 2021 22:17
-
-
Save jbadger3/56f02cee4ca3f0f5a7a7ef6298a8c402 to your computer and use it in GitHub Desktop.
Gists for the Medium post 'Paving A Road Between JSON And CoreData'
This file contains hidden or 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
private func downloadPosts(completion: @escaping ([PostData]?, Error?) ->Void) { | |
let postsURL = URL(string: "https://jsonplaceholder.typicode.com/posts")! | |
let downloadTask = urlSession.dataTask(with: postsURL) { data, response, error in | |
if let error = error { | |
completion(nil, error) | |
} | |
if let response = response as? HTTPURLResponse, | |
!(200..<300).contains(response.statusCode) { | |
return(completion(nil, PersistanceControllerError.Non200URLStatusCode(statusCode: response.statusCode))) | |
} | |
if let data = data { | |
do { | |
let posts = try JSONDecoder().decode([PostData].self, from: data) | |
return(completion(posts, nil)) | |
} catch { | |
return(completion(nil, error)) | |
} | |
} | |
} | |
downloadTask.resume() | |
} |
This file contains hidden or 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
private func importPosts(from posts:[PostData]) throws { | |
let privateContext = newPrivateContext() | |
privateContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy | |
privateContext.undoManager = nil | |
let batchSize = 10 | |
let numBatches = posts.count/batchSize | |
for batchNumber in 0..<numBatches { | |
let startIndex = batchNumber*batchSize | |
let endIndex = batchNumber == (numBatches - 1) ? posts.count - 1 : (startIndex + batchSize) | |
let dictionaryObjects = posts[startIndex..<endIndex].map({$0.propertyDictionary()}) | |
let batchInsertRequest = NSBatchInsertRequest(entityName: "Post", objects: dictionaryObjects) | |
let fetchResult = try privateContext.execute(batchInsertRequest) | |
if let batchInsertResult = fetchResult as? NSBatchInsertResult, | |
let success = batchInsertResult.result as? Bool { | |
if !success { | |
throw PersistanceControllerError.BatchInsertFailure | |
} | |
} | |
} | |
} |
This file contains hidden or 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
[ | |
{ | |
"userId": 1, | |
"id": 1, | |
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", | |
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" | |
}, | |
{ | |
"userId": 1, | |
"id": 2, | |
"title": "qui est esse", | |
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" | |
} | |
] |
This file contains hidden or 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
struct PostData: Decodable { | |
let userId: Int | |
let id: Int | |
let title: String | |
let body: String | |
} |
This file contains hidden or 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
extension PostData { | |
func propertyDictionary() -> [String: Any] { | |
//Used to translate JSON decoded struct to NSManagedObject Entity | |
let mirror = Mirror(reflecting: self) | |
var propertyDict: [String: Any] = [:] | |
for child in mirror.children { | |
if let propertyName = child.label { | |
propertyDict[propertyName] = child.value | |
} | |
} | |
return propertyDict | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment