Swift4.0中AFNetworking的橋接和使用
阿新 • • 發佈:2018-12-29
一、建立AFnetworking橋接檔案:
-
Github裡面down下來AFNetworking的壓縮包,解壓縮然後將裡面的AFNetworking和UIKit+AFNetworking這兩個資料夾直接拖進去要用的那個工程裡面去。
-
在Build Phrases下的Compile Sources新增所有匯入的.m檔案。我在實際操作中沒做到這步,因為我把資料夾拖進去之後,貌似Xcode就幫忙把這步做好了。
-
同樣在Build Phrases下的 Link Binary With Libraries 新增MobileCoreServices.framework、Security.framework、SystemConfiguration.framework這三個檔案。
-
建立"工程名-Bridging-Header.h"的檔案,因為是在Swift工程中用到OC的程式碼,所以要進行這個橋接的工作。在這個檔案裡面用#import "xx.h"這樣來包含我們剛剛放進來那些檔案的標頭檔案,所有都要。
-
寫好這個橋接標頭檔案之後,在工程的 Build Setting 條目下的 Swift Compiler - General 中配置 Objective-C Bridging Header 寫好是剛剛那個"工程名-Bridging-Header.h",把這個名字填上去。(如果你的專案還要在OC的檔案下呼叫Swift的方法的話,還要在Objective-C Generated Interface Header Name 裡配置成"工程名-Swift.h",這個"ProjectName-Swift.h"由系統生成,你也可以用command+滑鼠單擊來進入那個檔案來看裡面什麼樣子)
2、實現AFnetworking單例:
//單例: static let shared:NetworkManager = { let instence = NetworkManager() instence.requestSerializer = AFJSONRequestSerializer() instence.responseSerializer = AFHTTPResponseSerializer() instence.requestSerializer.setValue("application/json,text/html", forHTTPHeaderField: "Accept") instence.requestSerializer.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") return instence }()
3、實現AFnetworking的請求方式封裝:
import UIKit
//請求型別:
enum HTTPRequestType {
case GET
case POST
}
class NetworkManager: AFHTTPSessionManager {
//單例:
static let shared:NetworkManager = {
let instence = NetworkManager()
instence.requestSerializer = AFJSONRequestSerializer()
instence.responseSerializer = AFHTTPResponseSerializer()
instence.requestSerializer.setValue("application/json,text/html", forHTTPHeaderField: "Accept")
instence.requestSerializer.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
return instence
}()
func request(requestType:HTTPRequestType,urlString:String,parameters:[String:AnyObject]?,complated:@escaping(AnyObject?)->()){
let success = {
(tasks:URLSessionDataTask,json:Any) ->() in complated(json as AnyObject?)
}
let failure = {
(tasks:URLSessionDataTask?,error:Error) ->() in complated(nil)
}
if requestType == .GET {
get(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
}else{
self.post(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
}
}
}