公司前兩天要作個項目相似於PP紅包App Store應用刷榜項目,需求是用戶在safari中操做,而且支持一下幾點功能:前端
很遺憾這些功能前端都作不了,只能我開發一個助手,幫助他完成以上功能。 大體的實現思路就是,我把功能開發好,在app啓動時開啓http服務,他在safari中調用127.0.0.1:端口號/功能
,這種請求,由我來執行相應的操做。 說明:以上的一、2兩點都是經過bundle id
處理,而非URL Scheme
。swift
下載CocoaHTTPServer跨域
導入CocoaHTTPServer-master目錄下的Core、Vendor文件夾網絡
編輯以下代碼: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
建立HTTPConnection子類ide
在子類中實現以下方法學習
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"]
}
複製代碼