Perfect is an open source server side Swift framework, that help swift developers to build applications and other REST services. If we use Perfect to create a backend for an iOS application, it’s easy to stay consistent by sticking to one language and code style. In this tutorial, I will teach you to build a simple local server by Perfect.
A. Build a simple local server by Perfect
1.Use Terminal to create a project
- mkdir hello-perfect
- cd hello-perfect/
- swift package init –type executable
- swift package generate-xcodeproj
- open ./hello-perfect.xcodeproj/
2.Add a dependency Library
- Add the below red highlighted code in the Package.swift file
- Enter the below two command lines in Terminal
- swift package update
- swift package generate-xcodeproj
- import PerfectLib, PerfectHttp and PerfectHttpServer in main.swift file to check whether it added the dependency successfully.
3.Create Http Server
- Use Terminal to create webroot folder and create hello.txt in this folder.
- mkdir webroot
- touch webroot/hello.txt
- swift package generate-xcodeproj
- add below code in main.swift.
- edit scheme
- Build&Run
- Use web browser to visit http://localhost:8080/hello.txt
B.Simple Request Demo
1.A simple request
- Add below code in Main.swift file
- Use the web browser to visit http://localhost:8080
2.Return the requested data in JSON format
- Add below code in Main.swift file
- Use web browser to visit http://localhost:8080/hello
3.Simple GET request to receive parameter
- Add GET request code in Main.swift file
- Use web browser to visit http://localhost:8080/books/90
4.Simple POST request to receive parameters
Hi Charlie,
I like the tutorial, but I am having an issue when starting with B. Request Demo. When I try to navigate to the routes I keep getting i.e. “/hello, file does not exist”. Do you have any idea on how to fix this?
Thanks
Daniel