美文网首页
PART 1: Server Side Swift with P

PART 1: Server Side Swift with P

作者: allyessss | 来源:发表于2017-05-26 13:42 被阅读0次

说明: 此为个人学习笔记,推荐大家去raywenderlich学习
https://videos.raywenderlich.com/courses/77-server-side-swift-with-perfect/lessons/1

下载地址: demo

运行环境说明:

  • Xcode 8
  • swift 3

一、搭建一个简单的本地服务器

  1. 通过终端创建项目

  2. mkdir hello-perfect

  3. cd hello-perfect/

  4. swift package init --type executable

  5. swift package generate-xcodeproj

  6. open ./hello-perfect.xcodeproj/

  7. 添加PerfectlySoft依赖库

  8. 在Xcode中选中Package.swift, 添加以下代码


  9. 继续打开终端输入:swift package update

  10. 终端输入:swift package generate-xcodeproj

  11. 测试是否导入成功

  12. 用Xcode打开项目,选择Source—> hello-perfect —>main.swift

  13. 输入import PerfectLib import PerfectHTTP import PerfectHTTPServer
  14. 编译不报错即证明成功

  15. 添加文本,重新打包

  16. 打开终端创建文件

  17. mkdir webroot

  18. touch webroot/hello.tet

  19. 重新打包:swift package generate-xcodeproj

  20. 用Xcode打开项目,在hello.txt添加文字:hello, web server!

  21. 创建Http Server

  22. 在main.swift中输入
  23. edit scheme
  24. 选择,Options,选择Use custom working directory,目录为当前项目

     ![image.png](https://img.haomeiwen.com/i1969359/426e7e6096d030a8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    
  25. Build & Run
    成功的话控制台会输出:[INFO] Starting HTTP server on 0.0.0.0:9090
    注:如果失败的话,可能是端口被占用,更换端口即可

  26. 用浏览器敲入:http://localhost:9090/hello.txt,会看到刚才写的txt文件内容

至此,一个简单的HTTP服务器搭建完毕


二、简单请求示例

  1. 一个简单的请求
  1. 把被请求的数据用JSON格式返回
  • 定义一个方法将Str转换成JSON
  • 在写一个请求,build & run
  • 用浏览器访问http://localhost:9090/hello,会看到JSON格式的{"test":"testvolue","message":"Hello, JSON!”}
  1. 接收参数的简单GET请求
  • 添加一个请求
  • 浏览器输入验证
  1. 接收参数的简单POST请求
  • 添加一个post请求
  • 使用POST MAN验证

至此,简单的使用swift搭建本地服务器就结束了,如有疑问欢迎大家留言探讨

相关文章

网友评论

      本文标题:PART 1: Server Side Swift with P

      本文链接:https://www.haomeiwen.com/subject/pptxfxtx.html