Perfect是一个使用Swift编程语言开发Web和其他REST服务的框架,其主要目标是简化需要后端服务器软件的移动应用的开发,使开发人员可以使用同一种语言进行客户端和服务端开发。
因为是基于Swift开发,所以对于在iOS平台上可以达到客户端与服务端使用相同的类和一些封装好的工具,一定程度上可以减少代码重复,这一点有点像Android与Java服务器协作的好处,它完全支持使用Xcode开发和调试。由于Swift的开源特性,所以它必须能够在Linux上跑起来。
Perfect的工程可以在git上查看并且附有Demo,官网也有关于Perfect的详细文档与很多视频教程
git:https://github.com/PerfectlySoft/Perfect
官网:https://www.perfect.org
Perfect主要包含以下组件。详细查阅
http://www.infoq.com/cn/news/2015/11/perfect-swift
PerfectLib
PerfectLib是一个Swift模块,提供了一套进行服务端和客户端开发的核心工具。在许多情况下,客户端和服务端使用相同的API。
Perfect Server
Perfect Server是一个让Perfect能够运转的服务端组件。它是一个始终处于运行状态的独立进程,接受客户端连接、处理请求并返回响应。
搭建一个Perfect工程大致步骤如下:
- 创建工作空间引入Perfect库
- 设置工程
- 编码运行
准备工作:
下载Perfect库
推荐从git上下载源码,因为里面包含了可能用到的所有组件:![]()
解压Perfect库的压缩包,安装xcode的Perfect模板
![]()
打开这个工程直接run就可以
1. 创建工作空间引入Perfect库
1.1 创建工作空间
打开Xcode—>File—>New—>WorkPlace
创建一个PerfectDemo的工作空间,穿件完成后会生成一个PerfectDemo.xcworkspace文件该文件就是一个Xcode的工作空间。


1.2 引入PerfectLib与Perfect Server

注意添加选项的选择


添加完成后可以看到我们创建的PerfectDemo工作空间已经引入Perfect的依赖

接下来,创建一个PerfectDemo工程,该工程为正式的服务器工程:
推荐创建的时候以cocoaframwork的形式添加

注意添加工程的时候选择我们的工作空间为添加选项:

工程添加完成之后工作空间结构如下:

2. 设置工程
工程添加完成之后,开始设置我们的工程

具体设置项目如下:
Skip Install = No
Deployment Location = Yes
Installation Directory = /PerfectLibraries
Installation Build Products Location = $(CONFIGURATION_BUILD_DIR)
3. 编码运行
所有的设置成功之后,开始编写服务端代码:
创建PerfectMain.swift文件:
先运行一下官方的示例代码:
import Foundation
import PerfectLib
// This is the function which all Perfect Server modules must expose.
// The system will load the module and call this function.// In here, register any handlers or perform any one-time tasks.
public func PerfectServerModuleInit() {
// Install the built-in routing handler. // Using this system is optional and you could install your own system if desired.
Routing.Handler.registerGlobally() Routing.Routes["GET", ["/", "index.html"] ] = { (_:WebResponse) in return IndexHandler() }
// Check the console to see the logical structure of what was installed. print("\(Routing.Routes.description)")}
class IndexHandler: RequestHandler {
func handleRequest(request: WebRequest, response: WebResponse) {
response.appendBodyString("Index handler: You accessed path \(request.requestURI())") response.requestCompletedCallback()
}
}
代码编写完成之后,设置运行的Schema
选中PerfectDemo工程不要选到Perfect的库上去了
设置Excutable为我们之前添加的Perfect模板

设置完成之后,Run工程会启动一个PerfectServer Http程序,
表示我们的Perfect服务器已经启动,改程序面板可以设置服务器的端口号,ip,已经webroot目录等等

至此,Perfect服务器工程的创建与配置完成
工程可参照官方Demo或者该示例工程的
git: https://github.com/ilioner/PerfectServerDemo
原文地址:http://ilioner.github.io/2016/05/30/从头开始创建一个Swift的Perfect的服务端.html
网友评论