因为公司要求用OC进行开发,很久没用swift进行开发了,今天调接口发现不会了😹,难受的哟。弄了一会终于可以了,记录一下
测试接口地址
// 接口一
https://api.apiopen.top/getSongPoetry?page=1&count=20
// 接口二
https://api.apiopen.top/musicRankings
编码
// 添加两种类型 Post,Get
enum requestType {
case Post
case Get
}
class XNetworkTool : AFHTTPSessionManager {
// 单例
static let sharedTools : XNetworkTool = {
let tool = XNetworkTool()
tool.responseSerializer.acceptableContentTypes?.insert("text/html")
tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
return tool
}()
// GET/POST
func request(type: requestType, urlString: String, parameters: AnyObject?,successBlock: @escaping([String : Any]?) -> (), failureBlock: @escaping (Error?)->()) -> Void {
// 成功的闭包
let successBlock = { (task: URLSessionDataTask, responseObj: Any?) in
successBlock(responseObj as? [String : Any])
}
// 失败的闭包
let failureBlock = { (task: URLSessionDataTask?, error: Error) in
failureBlock(error)
}
// 进行请求
if type==requestType.Get {
// GET 担心包含中文处理一下
let urlStr = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
get(urlString, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock)
} else {
post(urlString, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock)
}
}
}
使用
XNetworkTool. sharedTools.request(type: .Get, urlString: "https://api.apiopen.top/musicRankings", parameters: nil, successBlock: { (dataDic) in
print(dataDic ?? Dictionary())
}) { (error) in
print(error ?? "")
}
网友评论