Make Reusable and More Clean HTTP Request Swift5

Suko Widodo
Dev Genius
Published in
2 min readJun 16, 2020

--

Hello guy, i want to share my story about learning development IOS apps with Swift 5 MVVM. Because basic me from android developer and there are some different patern about Ios development and android development. But i think ios development learning curve not really harder because swift it’s easier to learn espessially Swift5 and SwiftUi it.

I decided choose to learn Swift is because my experience doing projects with multi platform apps like react native with so many problem with native module. There are so many library in react native but sometime i found just work with android apps or just with ios only. Or i did not found anyone with native module that i need it.

When i build android apps with kotlin or java, there are library like retrofit was very helpfull, simple and clean. With that library the code look tidy and simple with MVP patern that i used. But when i start learning swift so many tutorial look just working code but not tidy and maintenable. Now i find nice patern to make http request look simple and reusable with MVVM observable patern.

First step is create RequestService to handle request to API like example below.

Then make codable model to mapping web service json response, there is simple way to do that. Open website https://swift4json or https://app.quicktype.io/ then copy your json response from postman and paste it to that web like this.

Then copy from generated code to your project, i usually save it to folder models but you can save it to another one.

Create your ViewModel by create a class with have parent class name ObservableObject then you can call the API like this. I did not save token with NSUserDefaults is not secure or encrypted it can be easily opened and read, both on device and when synced to a Mac.

NSUserDefaults is a good place for things like preferences and config info, it’s not a good place for anything sensitive, like passwords or token. I used library named KeychainSwift to saving token.

And last on view you just call the ViewModel and observe it response to parsing to view.

Now you can add more request api just add below that login function. I hope this tutorial can be useful for you and thank you for reading. give claps to support us ;-). And see you.

--

--