說明: 此為個(gè)人學(xué)習(xí)筆記,推薦大家去raywenderlich學(xué)習(xí)
https://videos.raywenderlich.com/courses/77-server-side-swift-with-perfect/lessons/1
下載地址: demo
運(yùn)行環(huán)境說明:
- Xcode 8
- swift 3
一、搭建一個(gè)簡(jiǎn)單的本地服務(wù)器
通過終端創(chuàng)建項(xiàng)目
mkdir hello-perfect
cd hello-perfect/
swift package init --type executable
swift package generate-xcodeproj
open ./hello-perfect.xcodeproj/
添加PerfectlySoft依賴庫
-
在Xcode中選中Package.swift, 添加以下代碼
繼續(xù)打開終端輸入:swift package update
終端輸入:swift package generate-xcodeproj
測(cè)試是否導(dǎo)入成功
用Xcode打開項(xiàng)目,選擇Source—> hello-perfect —>main.swift
-
輸入import PerfectLib import PerfectHTTP import PerfectHTTPServer
編譯不報(bào)錯(cuò)即證明成功
添加文本,重新打包
打開終端創(chuàng)建文件
mkdir webroot
touch webroot/hello.tet
重新打包:swift package generate-xcodeproj
用Xcode打開項(xiàng)目,在hello.txt添加文字:hello, web server!
創(chuàng)建Http Server
-
在main.swift中輸入
-
edit scheme
-
選擇,Options,選擇Use custom working directory,目錄為當(dāng)前項(xiàng)目
 Build & Run
成功的話控制臺(tái)會(huì)輸出:[INFO] Starting HTTP server on 0.0.0.0:9090
注:如果失敗的話,可能是端口被占用,更換端口即可-
用瀏覽器敲入:http://localhost:9090/hello.txt,會(huì)看到剛才寫的txt文件內(nèi)容
至此,一個(gè)簡(jiǎn)單的HTTP服務(wù)器搭建完畢
二、簡(jiǎn)單請(qǐng)求示例
- 一個(gè)簡(jiǎn)單的請(qǐng)求
-
繼續(xù)在main.swift輸入
- 用瀏覽器敲入:http://localhost:9090/,會(huì)看到Hello perfect.
- 把被請(qǐng)求的數(shù)據(jù)用JSON格式返回
-
定義一個(gè)方法將Str轉(zhuǎn)換成JSON
-
在寫一個(gè)請(qǐng)求,build & run
- 用瀏覽器訪問http://localhost:9090/hello,會(huì)看到JSON格式的
{"test":"testvolue","message":"Hello, JSON!”}
- 接收參數(shù)的簡(jiǎn)單GET請(qǐng)求
-
添加一個(gè)請(qǐng)求
-
瀏覽器輸入驗(yàn)證
- 接收參數(shù)的簡(jiǎn)單POST請(qǐng)求
-
添加一個(gè)post請(qǐng)求
-
使用POST MAN驗(yàn)證
至此,簡(jiǎn)單的使用swift搭建本地服務(wù)器就結(jié)束了,如有疑問歡迎大家留言探討











