美文网首页Swift
Swift Web 简单体验

Swift Web 简单体验

作者: 当阳桥 | 来源:发表于2017-10-10 17:44 被阅读17次

趁这两天工作不太忙,感受了一下swift web,目前好像Perfect框架在github上星星最多,所以我就用Perfect来做做测试,于是就到官网看看:https://www.perfect.org/docs/gettingStarted_zh_CN.html,按照快速上手文档前面介绍,配置好环境变量,最终会在根目录添加一个

屏幕快照 2017-10-10 下午4.51.48.png 工程文件,里面大致有如下内容:
屏幕快照 2017-10-10 下午4.52.56.png 启动可执行文件,选择Mac启动服务器
屏幕快照 2017-10-10 下午4.56.39.png 之后在浏览器中输入:http://localhost:8181/你将看到,说明服务器联通了
屏幕快照 2017-10-10 下午5.01.03.png

现在我们主要关注项目中的main.swift 文件,我门要做的是:

在文件中导入 import Foundation,因为后面我们会用来json解析一些请求数据,接下来就是按照下面的处理来添加一些请求回调,我想要做的实验是:在模拟器上通过post、get请求调用这个服务器,然后通过下面的handler函数给我反回一下参数:content、img、以及post请求传过来的httpBody、get请求传过来的查询参数,所以我做了如下操作:

func handler(data: [String:Any]) throws -> RequestHandler {
    return {
        request, response in
        
        let contentType = request.header(HTTPRequestHeader.Name.contentType)
        let method = request.method
        var respbody:[String:String] = ["content":"success","img":"http:https://img.haomeiwen.com/i3343569/93b8bb59dba2d33a.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"]
        if method == .post &&  contentType == "application/json" {
            print("post request")
            let result =  request.postParams.first
            print(result?.0 ?? "")
            let dicString = result?.0
            
            let data = dicString?.data(using: .utf8)
            
            let dic:[String:String] = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments)  as! [String : String]
            
            for (key,value) in dic {
                respbody[key] = value
            }
            try! response.setBody(json: respbody)
        }else if method == .get && contentType == "application/json" {
    
            print("get request")
            response.setHeader(.contentType, value: contentType!)
            for (key,value) in request.queryParams {
                respbody[key] = value
            }
            
            try! response.setBody(json: respbody)
            
        }else{
            
            // Respond with a simple message.
            response.setHeader(.contentType, value: "text/html")
            response.appendBody(string: "<html><title>Hello, world!</title><body>Hello, world!</body></html>")
        }
        // Ensure that response.completed() is called when your processing is done.
        response.completed()
    }
}

由于这个模版是按照标准框架来写的,里面设计到拦截器、过滤器、路由等,路由代表配置路径的映射关系,下面我们配置一个POST、GET路由。回调处理都映射到上面配置的handler函数中去。出于简单考虑,把下面routes中的过滤器那一个关闭掉,免得引起麻烦。

let confData = [
    "servers": [
        // Configuration data for one server which:
        //  * Serves the hello world message at <host>:<port>/
        //  * Serves static files out of the "./webroot"
        //      directory (which must be located in the current working directory).
        //  * Performs content compression on outgoing data when appropriate.
        [
            "name":"localhost",
            "port":8181,
            "routes":[
                ["method":"GET", "uri":"/**", "handler":handler],
                ["method":"POST", "uri":"/**", "handler":handler],
//                ["method":"get", "uri":"/**", "handler":PerfectHTTPServer.HTTPHandler.staticFiles,
//                 "documentRoot":"./webroot",
//                 "allowResponseFilters":true]
            ],
            "filters":[
                [
                "type":"response",
                "priority":"high",
                "name":PerfectHTTPServer.HTTPFilter.contentCompression,
                ]
            ]
        ]
    
    ]
]

接下来用xcode创建另一个工程用于在模拟器上测试post、get请求,并返回json格式的数据:代码直接贴过来:

//
//  ViewController.swift
//  Test
//
//  Created by 不知道叫啥 on 2017/9/15.
//  Copyright © 2017年 不知道叫啥. All rights reserved.
//

import UIKit

class ViewController: UIViewController{    
    var imageView:UIImageView?
    override func viewDidLoad() {
        super.viewDidLoad()

        let reloadBtn:UIButton? = UIButton.init(frame: CGRect.init(x: 10, y: 100, width: 80, height: 40))
        reloadBtn?.layer.backgroundColor =  UIColor.yellow.cgColor
        reloadBtn?.layer.borderWidth = 0.5
        reloadBtn?.layer.cornerRadius = 3
        reloadBtn?.layer.masksToBounds = true
        reloadBtn?.setTitle("POST", for:.normal)
        reloadBtn?.setTitleColor(UIColor.blue, for: .normal)
        reloadBtn?.backgroundColor = UIColor.white
        reloadBtn?.addTarget(self.target, action: #selector(postAction), for: .touchUpInside)
        self.view.addSubview(reloadBtn!)
        
        
        let getBtn:UIButton? = UIButton.init(frame: CGRect.init(x: 120, y: 100, width: 80, height: 40))
        getBtn?.layer.backgroundColor =  UIColor.yellow.cgColor
        getBtn?.layer.borderWidth = 0.5
        getBtn?.layer.cornerRadius = 3
        getBtn?.layer.masksToBounds = true
        getBtn?.setTitle("GET", for:.normal)
        getBtn?.backgroundColor = UIColor.white
        getBtn?.setTitleColor(UIColor.blue, for: .normal)
        getBtn?.addTarget(self.target, action: #selector(getAction), for: .touchUpInside)
        self.view.addSubview(getBtn!)
       
        self.imageView = UIImageView.init(frame: self.view.frame)
        self.view.addSubview(self.imageView!)
    }
    
    func postAction()  {
        self.postWithPath(path: "http://localhost:8181/v1/call1", paras: ["sex":"2","age":"18","type":"POST"], success: { (dic) in
            print("success")
        }) { (error) in
            print(error)
        }
    }
    
    func getAction()  {
        self.getWithPath(path: "http://localhost:8181", paras: ["sex":"2","age":"18","type":"get"], success: { (dic) in
            print(dic)
        }) { (error) in
            print(error)
        }
    }
        
    // MARK:- get请求
    func getWithPath(path: String,paras: Dictionary<String,Any>?,success: @escaping ((_ result: Any) -> ()),failure: @escaping ((_ error: Error) -> ())) {
        
        var i = 0
        var address = path
        if let paras = paras {
            
            for (key,value) in paras {
                if i == 0 {
                    address += "?\(key)=\(value)"
                }else {
                    
                    address += "&\(key)=\(value)"
                }
                i += 1
            }
        }
        
        let url = URL(string: address.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)
        
        let session = URLSession.shared
        
        var request = URLRequest.init(url: url!)
        
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        
         let datatask = session.dataTask(with: request) {  (data, respond, error) in
            
            if let data = data {
                let r = String.init(data: data, encoding: .utf8)
                
                print(r ?? "empty")
                
                let result = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:String]
                
                guard (result != nil) else {
                    return
                }
                let imageURL = URL.init(string: result!["img"]!)
                let data = try! Data.init(contentsOf: imageURL!)
                
                DispatchQueue.main.async(execute: {
                    self.imageView?.image =  UIImage.init(data: data)
                })
                success(result!)
                
            }else {
                failure(error!)
            }

        }
        datatask.resume()
    }
    
    
    // MARK:- post请求
    func postWithPath(path: String,paras: Dictionary<String,Any>?,success: @escaping ((_ result: Any) -> ()),failure: @escaping ((_ error: Error) -> ())) {
        
        let url = URL(string: path)
        var request = URLRequest.init(url: url!)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        let body = try! JSONSerialization.data(withJSONObject: paras!, options: .prettyPrinted)
        let paramsString = String.init(data: body, encoding: .utf8)
        let dataString = paramsString?.data(using: .utf8)
        request.httpBody = dataString
        let session = URLSession.shared
        
        let dataTask = session.dataTask(with: request) { (data, respond, error) in
            
            if let data = data {
                
                let r = String.init(data: data, encoding: .utf8)
                
                print(r ?? "empty")
                
                let dic = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as! Dictionary<String,String>
                
                success(dic ?? ["content":"empty"])
                
                let imageURL = URL.init(string: dic!["img"]!)
                let data = try! Data.init(contentsOf: imageURL!)
                
               // 回到主现程
                DispatchQueue.main.async(execute: {
                    self.imageView?.image =  UIImage.init(data: data)
                })
                
            }else {
                failure(error!)
            }
        }
        dataTask.resume()
    }

}


接下来观察输出日志,观看模拟器

屏幕快照 2017-10-10 下午5.29.02.png
上面的这个图片是今天早上在简书上看到的一个国企旅游的拍的照片感觉很美,有机会一定去内蒙玩玩http://www.jianshu.com/p/92a890e760d9真的很美

over!

由于对模版工程的代码不是很清楚,调试时候也只是大致断点看看,里面设计到一些拦截器、过滤器、路由等并没有具体去深究,后面会慢慢查看具体实现过程。希望swift早日登上web开发的舞台!

相关文章

网友评论

    本文标题:Swift Web 简单体验

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