最近项目中使用了Moya来做网络请求,于是对其简单封装一下以方便使用
Moya: https://github.com/Moya/Moya

自定义插件

1
2
3
4
5
6
7
8
9
10
11
12
13
final class RequestLogPlugin: PluginType{

func willSend(_ request: RequestType, target: TargetType) {
Log("[URL]:\(request.request!.url!.absoluteString)")
if(request.request?.httpBody != nil){
let JSONString = NSString(data:(request.request?.httpBody!)!,encoding: String.Encoding.utf8.rawValue)
Log("[Param:]---------------------------------[")
Log(JSONString!)
Log("[Param:]---------------------------------]")
}
}

}

这里主要是添加了两个打印信息,一个请求的接口地址,一个是请求时的参数,方便在开发过程中调试。

请求类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import Moya
import SwiftyJSON

let MAProvider = MoyaProvider<MultiTarget>( plugins: [RequestLogPlugin()])
struct AHNetwork {

static func request(_ target:MultiTarget,success successCallback: @escaping (String) -> Void,failure failureCallback: @escaping (MoyaError) -> Void){

MAProvider.request(target) { (result) in
switch result {
case let .success(response):
let jsonData = response.data
let jsonString = String.init(data: jsonData, encoding: .utf8)
Log("[Reponse:]---------------------------------[")
Log(jsonString!)
Log("[Reponse:]---------------------------------]")
successCallback(jsonString!)
case let .failure(error):
Log("[Error:]\(String(describing: error.errorDescription))")
failureCallback(error)
}
}
}

}

1,定义一个Provider使用我们刚定义的plugin
2,将请求方法都封装在AHNetwork中的request方法中,此方法需传入target,一个success的逃逸闭包和failure的逃逸闭包。
2,这里的Log函数为一个全局的打印函数,在本文最后贴出。
3,在这个函数内可以根据实际的业务需求添加一些需要统一处理的逻辑,比如token过期,错误处理之类的逻辑。

API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import Moya

public enum AHVideoAPi {

case fetchVideoCategory
case fetchVideoCategoryDetail(_ id:Int)

}

extension AHVideoAPi : TargetType{

public var baseURL: URL {
return URL(string: "https://api.apiopen.top")!
}

public var path: String {
switch self {
case .fetchVideoCategory:
return "/videoCategory"
case .fetchVideoCategoryDetail:
return "/videoCategoryDetails"

}
}

public var method: Moya.Method {
switch self {
case .fetchVideoCategory,.fetchVideoCategoryDetail:
return .post
}
}

public var sampleData: Data {
return "{}".data(using: String.Encoding.utf8)!
}

public var task: Task {
switch self {
case .fetchVideoCategory:
return .requestPlain
case .fetchVideoCategoryDetail(let id):
let params: [String: Any] = ["id":id]
return .requestParameters(parameters: params,encoding: URLEncoding.default)

}
}

public var headers: [String : String]? {
return nil
}

Api类就是Moya的常规使用,这里就不多做解释了

请求案例

1
2
3
4
5
AHNetwork.request(MultiTarget(AHVideoAPi.fetchVideoCategory), success: { (_) in
/// do something success
}) { (_) in
/// do something error
}

Log函数

1
2
3
4
5
6
7
8
9
10
func Log<T>(_ message:T,file:String = #file,funcName:String = #function,lineNum:Int = #line){

#if DEBUG

let file = (file as NSString).lastPathComponent;

print("\(file):(\(lineNum))--\(message)");

#endif
}
Swift中的Extension