CocoaHttpServer使用

我是怎麼開始接觸它的?

公司前兩天要作個項目相似於PP紅包App Store應用刷榜項目,需求是用戶在safari中操做,而且支持一下幾點功能:前端

  1. 判斷設備是否安裝某app
  2. 若是安裝啓動app
  3. 獲取到設備和網絡信息
  4. ...

很遺憾這些功能前端都作不了,只能我開發一個助手,幫助他完成以上功能。 大體的實現思路就是,我把功能開發好,在app啓動時開啓http服務,他在safari中調用127.0.0.1:端口號/功能,這種請求,由我來執行相應的操做。 說明:以上的一、2兩點都是經過bundle id處理,而非URL Schemeswift

學習它能作啥?

  1. app開服務供本地的其餘項目訪問(例如:safari)
  2. 局域網內傳文件
  3. ...

怎麼用?

  1. 下載CocoaHTTPServer跨域

  2. 導入CocoaHTTPServer-master目錄下的Core、Vendor文件夾網絡

  3. 編輯以下代碼:app

    let localHttpServer = HTTPServer()
    localHttpServer.setType("_http.tcp")
    // 設置端口
    localHttpServer.setPort(53246)
    localHttpServer.setConnectionClass(HTTPConnection.classForCoder())
    do {
        try localHttpServer.start()
        print("開啓成功")
        print(localHttpServer.listeningPort())
    } catch {
        printLog(error)
        print("開啓失敗")
    }
    複製代碼

    如今是能夠訪問了,那麼怎麼處理請求呢?tcp

處理本地請求

  1. 建立HTTPConnection子類ide

  2. 在子類中實現以下方法學習

    override func supportsMethod(_ method: String!, atPath path: String!) -> Bool {
        print("supportsMethod - method:\(method!) - path:\(path!)")
        return true
    }
    
    override func expectsRequestBody(fromMethod method: String!, atPath path: String!) -> Bool {
        print("expectsRequestBody - method:\(method!) - path:\(path!)")
        return true
    }
    
    override func httpResponse(forMethod method: String!, uri path: String!) -> (NSObjectProtocol & HTTPResponse)! {
        // 獲取應用信息
        if path.hasPrefix("/getAppInfo") {
            do {
                let respDic = ["bundleIdentifier": Bundle.main.bundleIdentifier,
                               "version": shortVersionString,
                               "build": versionString,
                               "appName": displayName] // 應用信息
                let respData = try JSONSerialization.data(withJSONObject: respDic, options: JSONSerialization.WritingOptions.init(rawValue: 0))
                return LYHTTPDataResponse(data: respData)
            } catch {
            }
        }
        return httpResponse(forMethod: method, uri: path)
    }
    複製代碼

注意:

若是訪問時出現跨域問題,嘗試添加以下代碼:ui

override func httpHeaders() -> [AnyHashable : Any]! {
    return ["Content-type": "*",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Credentials": "true",
            "Access-Control-Allow-Methods": "POST, GET, OPTIONS",
            "Access-Control-Max-Age": "3600",
            "Access-Control-Allow-Headers": "Origin, Referer, User-Agent, Accept"]
}
複製代碼
相關文章
相關標籤/搜索