最近在开发一个新Swift的项目,简书没怎么写,会陆续跟新我在项目中遇到或者解决的问题!
项目的开始,必定是先使用cocoapods导入所依赖的框架
1.Alamofire Star:24000
Alamofire 是 Swift 语言编写的 HTTP 网络库。相当于OC中的AFNetworking
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!
target '<Your Target Name>' do
pod 'Alamofire', '~> 4.4'
end
简单的使用
1.Use GET
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}
2.响应
响应可以序列化成你想要的类型data,json,string...
.responseString { response in
print("Response String: \(response.result.value)")
}
.responseJSON { response in
print("Response JSON: \(response.result.value)")
}
.responseData { response in
print("Response JSON: \(response.result.value)")
}
3.也可以添加验证 statusCode contentType
Alamofire.request("https://httpbin.org/get")
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseData { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}
4.上传图片
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(self.getData(image: value), withName: "上传的key", fileName: "文件名", mimeType: "类型"->"image/jpg")
// 其他参数
multipartFormData.append("其他参数value".data(using: .utf8)!, withName: "其他参数key")
},
to: "https://httpbin.org/post",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
// 图片限制大小500k
fileprivate func getData(image: UIImage) -> Data {
var multiple = CGFloat(1.0)
var imageData = UIImageJPEGRepresentation(image, multiple) ?? Data()
var sizeOriginKB = imageData.count / 1024
let maxSize = 500
while sizeOriginKB > maxSize && multiple > 0.1 {
multiple = multiple - 0.1
imageData = UIImageJPEGRepresentation(image, multiple) ?? Data()
sizeOriginKB = imageData.count / 1024
}
return imageData
}
就先说到这些基础使用其余的可以去git上都很全面
2.Moya Star:6600
- 网络层这一块用Alamofire,如同于在oc中用AFNetworking.但是,如果你直接使用的话,会使得各种网络请求操作分布很凌乱,Moya是对 Alamofire的进一步封装。
- 秉着实用主意直接上代码
// MARK:- 属性
static let sharedInstance = Networking()
let requestTimeoutClosure = { (endpoint: Endpoint<Service>, done: @escaping MoyaProvider<Service>.RequestResultClosure) in
guard var request = endpoint.urlRequest else { return }
request.timeoutInterval = 20.0 //设置请求超时时间
done(.success(request))
}
public var provider = MoyaProvider<Service>()
provider = MoyaProvider<Service>(requestClosure: requestTimeoutClosure)
发送请求
public func requestData(type: Service, finished : @escaping (_ result : String?) -> ()) {
provider.request(type) { result in
switch result {
case let .success(response):
let json: String = self.parserXML.parserXML(data: response.data)
break
case let .failure(error):
DDLog(error.localizedDescription)
break
}
}
}
可能会产生疑问 地址呢 参数呢
Moya使用枚举来枚举你所有的 API targets。你可以把所有关于这个API的信息放在这个枚举类型中。
这个枚举类型用来在编译的阶段给每个target提供具体的信息,每个枚举的值必须有发送http request需要的基本参数,像url,method,parameters等等。这些要求被定义在一个叫做TargetType的协议中,在使用过程过我们的枚举类型需要服从这个协议。通常我们把这一部分的代码写在枚举类型的扩展里。
public enum Service {
case .login(account: String, password: String)
}
extension Service: TargetType {
public var baseURL: URL {
return URL(string: URL_PREFIX)!
}
public var path: String {
return "/xxxx/xxxxx/gateway.in"
}
public var method: Moya.Method {
switch self {
case .login:
return .post
}
}
public var parameters: [String: Any]? {
switch self {
case .login(let picType, let picFile, let paymentId, _):
return ["account": account, "password":password]
}
}
public var parameterEncoding: ParameterEncoding {
return URLEncoding.default
}
public var sampleData: Data {
return "{}".data(using: String.Encoding.utf8)!
}
}
网友评论