Swift Perfect server development (solve all Difficult miscellaneous diseases)

The current Swift server development, there are four main frame perfect, vapor, kitura, zewo excellent and difference between them, you have to understand, here the author use perfect framework to build from the practical application, and get a small half, encounter various pits, during various fill, through numerous data, xianlaiwushi finishing under the.
write in accordance with the author’s own process

A: MySql article

Why use MySQL it, in order to platform compatibility, in fact, when the author also wrote with Coredata, SQLite stored data, but the use of MySQL is the most rational.
1, check to see if the MySQL
commond+shift+go is installed to enter /usr/local to see if there is a

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 10.59.46.png

If the
and the like, that you have installed, if not, please go to the official website to download
is connected directly to the download page to download and install https://dev.mysql.com/downloads/mysql/

2, using navcat or other tools to connect to the database, the author used the navcat
click on the upper left corner myconnect-> MySQL

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.05.32.png

A name as connectionName, port default, userName and password do not tube, the important thing Encoding

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.06.59.png

The
encoding format is an option under the UTF-8 that is the default, and what does it do? If you tick, you will find that you save the Chinese characters are garbled, so do not check it.
3 connection prompt you for the root password error
here I also encountered, MAC installation, no password, I was installed as if this is the case, this is your
http://jingyan.baidu.com/article/ 63f236280a11680208ab3d91.html
connection password reset put on it, I don’t burden

Two: Perfect build article

The http://www.cnblogs.com/ludashi/p/6145344.html
reference in building before, suggest that you get to know Swift package (package manager) the role of
1, open a terminal and enter into this framework where you want to store, where you can
.

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.17.15.png

2, download the framework template, use the terminal to complete

Git clone https://github.com/PerfectlySoft/PerfectTemplate

CD to the template, LS you can see the following

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.20.11.png

3, change the name of the project, and improve the template content
open the folder package file

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.22.40.png

1, name) is corresponding to the project name, here you want to change the project name, its role in the back you will see
2),.Package (url:) which is the version of the configuration dependencies here also need to add some

.Package (url: https://github.com/PerfectlySoft/Perfect-HTTPServer.git, majorVersion: 2),.Package (url: log //Request request filter "https://github.com/dabfleming/Perfect-RequestLogger.git", majorVersion: 0), the log / / writes the specified file.Package (url: https://github.com/PerfectlySoft/Perfect-Logger.git, majorVersion: 0, minor: 0), //MySql.Package (url: database package on "https://github.com/PerfectlySoft/Perfect-MySQL.git", majorVersion: 2, minor: 0)
Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.25.20.png

3, configuration dependent package

Enter Swift build in terminal

This process is long and boring, patience, if there is a problem please retry
1), the first type of error:

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.30.22.png

this error shows that your Package file configuration problems, please follow the above I said the configuration
2), the second type of error

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.29.51.png

find links in the corresponding file, delete, re build

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.33.06.png

if you packages enough twelve folders, as above, this time also reported the error of the first kind, so you do not care for him, then the next step of
4, the main.swift file main.swift file to replace
using the above reference in the article in demo replace the main.swift file system, because I feel it it is better by using
https://github.com/lizelu/PerfectDemo
5,
swift generated workspace file server, how also can use Xcode to open the operation right

Terminal input swift package generate-xcodeproj
Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.44.33.png

this time you can use Xcode to open the run

Runtime error solution

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.45.52.png

solution reference article http://www.jianshu.com/p/c117294e2442

Error Header'/usr/local/include/mysql/mysql.h'this error is because we store the path to the mysql.h file and the path it refers to is different. The MySQL path installed with Homebrew is indeed correct. Solution: Click Finder to select Folder into the /usr/local directory, you will find the MySQL folder in the folder, find the corresponding mysql.h get directory path will error in the module.modulemap file to modify your own path on it. Here I finally the path is /usr/local/mysql-5.7.15-osx10.11-x86_64/include/mysql.h two ld: library not found for error -lmysqlclient for architecture x86_64 solution: find the MySQL in Target, found with the MySQL folder under the Lib folder path Library Search Paths. I find PerfectTemplate /usr/local/Cellar/mysql/5.7.16/lib is found in Target Other Linker Flags and -L/usr/local/Cellar/mysql/5.7.16/lib in the Lib directory to find the corresponding mysqlclient file.

When all errors are resolved, you can run

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.49.31.png

this time, you can then browser access to your local interface

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.51.34.png

Three: interface application

1, add get request has been taken as an example

Routes.add (method:.Get / / back pictures, uri: /img, handler: response in let {request, docRoot = request.documentRoot / / get the user upload the get parameters of let name request.param (name: = "name"); do cat ("{//let = File / (docRoot) / 6.jpg" let cat (String.init) = File (format: "/Users/ybon/Desktop/ personal picture / game /%@" name! Let imageSize)); cat.size = let imageBytes = try (cat.readSomeBytes count: imageSize response.setHeader (.ContentType), value: MimeType.forExtension ("JPG") response.setHeader (.ContentLength), value: (imageBytes.count / response.setBody) ") (bytes: imageBytes)} catch {response.status =.InternalServerError response.setBody (string:" request processing is wrong: / (error) response.complet} ") Ed ()})

Test interface
in browser

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 11.56.29.png

2, add post request

Add a new routes.add (method:.Post / uri:, /addFriend) {(request, respons) in var name; if let = "namer = request.param (name: name) {name = namer;} var addr =" if "; let addrr = request.param (name: addr) {addr = addrr var DESC;} =" if "; let descr = request.param (name: DESC) {desc = descr;} zySql.sqeryDB (sqlTxt: INSERT INTO namelist (name, age, addr, desc (VALUES) / (name) ', 23' / '/' (addr), (DESC) ')" let dic:); [String: Any] = "code": "[200"]; respons.setHeader (.ContentType value: application/json) do respons.setBody (json: DIC) {try} catch {print ("JSON conversion failure" (respons.completed)})}

This interface you can use AFN to test the
more usage, we can explore their own

Four: MySQL advanced articles

I wrote a MySQL class, commond+n create a file

Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 12.04.03.png
Swift Perfect server development (solve all Difficult miscellaneous diseases)
screen snapshot 2017-05-03 12.04.13.png

1, import header file

Import Foundation MySQL import mysqlclient import import PerfectLogger

2, configure the MySQL address, port, user name, password

Var host: String{get{return "127.0.0.1";}} var port: UInt32{get{return 3306;}} var user: String{get{return "root";}} var password:String{get{return "ybon";}}

3, create a MySQL object

Private var mysql:MySQL; (self.connectDataBase); self.selectDataBase (name: "test_new");

4, connect database

Private func (connectDataBase) {if MySQL = = nil {MySQL = MySQL.init (//socket);} let connected random parameter = MySQL?.connect (host: host, user: user, password: password, db: "test_new" port:, port, socket: zy01, flag: 0); guard (else{LogFile.error MySQL connected! (.ErrorMessage? ())!} (LogFile.info; return); "database connection success");}

5, select the database scheme

Func selectDataBase (name:String) {guard (MySQL?.selectDatabase (named: name) else{(LogFile.error)! "Database compilation failed, error code: (MySQL /.ErrorCode) (?) (MySQL / /n error explanation:.ErrorMessage (?))"); return;} LogFile.info ("connected schema:/ (name)"});

6, additions and deletions to change method

Func sqeryDB (sqlTxt:String) {let querySuccess_create = MySQL?.query (statement: sqlTxt) guard querySuccess_create! Else{LogFile.error ("failure"); return LogFile.error ("success"});}

7, check all data

Func getallFriend (->); Array< Dictionary< String, Any> >? {/ * sqeryDB (sqlTxt: insert into namelist (name) values ('Zhang Xianhong') "); save Chinese garbled solution 1 right click the database link select the link attribute 2 switch to the Advanced tab to check the use of MySQL the character set in front of the removed success / let = MySQL?.query (statement:" select *from namelist "); guard success else{LogFile.error! (" failed "); return nil;} LogFile.error (" success "); let result = MySQL?.storeResults (VaR); arr:Array< Dictionary< String, Any> > Array.init (result); =; {(callback:?.forEachRow (row) in var dic:Dictionary< String, Any> Dictionary.init = (); If row[0]! Nil{dic[= "name"] = row[0]! As String}else{; dic["name"] = "if";} row[1]! = nil{dic[] "age" = row[1]! As String}else{; dic["age"] = "if";} row[2]! = nil{dic["addr"] as String;}else{= row[2]! Dic["addr"] = "if";} row[3]! = nil{dic[] "desc" = row[3]! As String}else{; dic["desc"] = "if";} row[4]! = nil{dic[] "sex" = row[4]! As String}else{dic[sex ";"] = "if";} row[5]! = nil{dic[] "Id" = row[5]! As String}else{; dic["Id"] = "";} Arr.append (DIC);}) return arr;}

Author Demo download address https://github.com/zhangxianhongx/PerfectService