- 开发语言:
前端:swift
后端:Java
1.Alamofire版本
pod 'Alamofire', '~> 4.5'
2.swift主要方法
typealias StringVoidBlock = (String?)->(Void)
typealias JSONVoidBlock = (JSON)->(Void)
/// 多图上传,带参数(必须用formdata表单上传)
/// - Parameters:
/// - apiName: 接口方法名
/// - method: HTTP请求的方法名(POST、PUT等)
/// - params: 需要传递的参数
/// - images: 上传的图片数组
/// - success: 成功回调
/// - fail: 失败回调
static func upload(apiName:String,method:HTTPMethod,params:[String:Any]?,images:[UIImage],success: JSONVoidBlock?,fail:StringVoidBlock?) {
let fullStr = SERVERURL + apiName
/// 设置公共参数
let token = "token" /// 这是你们httpHeader用到的token
let httpHeader: HTTPHeaders = [
"Authorization": token,
"Content-type": "multipart/form-data"
]
Alamofire.upload(multipartFormData: { (multipartFormData) in
if params != nil {
for (key, value) in params! {
let data_ = "\(value)".data(using: String.Encoding.utf8)!
HLog(message: data_)
multipartFormData.append(data_, withName: key)
}
}
for index in 0..<images.count {
let img = images[index]
if let imgData = img.jpegData(compressionQuality: 0.2) {
multipartFormData.append(imgData, withName: "files",fileName: "image_\(index).png", mimeType: "image/png")
}
}
}, to: fullStr ,method: method,headers: httpHeader) { (encodingResult) in
// SessionManager.MultipartFormDataEncodingResult
print("UPLOAD请求url----->" + fullStr)
print("UPLOAD请求params-----> \(params ?? [:])")
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
/// 上传成功
guard response.result.isSuccess else {
/// 网络链接错误或者服务器故障
if fail != nil {
fail!("网络链接错误或者服务器故障")
}
return
}
let json = JSON(response.result.value as Any)
let msg = json["message"].stringValue
let code = json["code"].intValue
if code == 200 {
/// 成功
if success != nil {
success!(json["data"])
}
print(json["data"])
}else if code == 401 {
/// token 失效,重新登录
if fail != nil {
fail!("登录失败,请重新登录")
ELUser.share.userModel = nil
toLogin()
}
}else {
/// 失败
if fail != nil {
fail!(msg)
}
}
}
case .failure(let encodingError):
if fail != nil {
fail!(encodingError.localizedDescription)
}
}
}
}
3.如何使用
/// 提交修改(上传图片)
private func requestTest() {
/// 1.拼接URL
let urlStr = "https://www.baidu.com"
/// 参数
let jsonStr = NSObject.getJSONStringFromDictionary(dictionary: [
"key_A" :"AAAA",
"key_B" : "BBBB",
])
let params = [
"testParams" : jsonStr,
"otherParams" : NSObject.getJSONStringFromArray(arr: ["A","B","C"])
] as [String : Any]
let uploadImages = images[0..<images.count]
weak var weakSelf = self
ELHttpTool.upload(apiName: urlStr,method: .put,params: params, images: uploadImages , success: { (result) -> (Void) in
print("上传成功!")
}
}) { (errStr) -> (Void) in
if errStr != nil {
MBProgressHUD.showMsg(toView: KeyWin, msg: errStr!)
}
}
}
- 注意点:
如果后端接不到数据,那么你要和后端确认,他那边是否是JSON反序列化的。如果是,应该没问题,如果不是,要看他是怎么接收的数据。Alamofire框架已经很强大了,基本没啥问题,抽空多看看他的源码就知道了。一般出了问题,主要还是和后端的兄弟姐妹们积极沟通,断点调试最好。
最后
上面用到的JSON序列化方法如下:
import Foundation
extension NSObject {
// 字符串过滤 fillter
class func fillterList(lastList:[String],searchStr:String) -> [String] {
let arr:[String]?
arr = lastList.filter({ (restaurant) -> Bool in
return restaurant.localizedCaseInsensitiveContains(searchStr)
})
return arr!
}
/**
* 字典转换为JSONString
*/
class func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
if (!JSONSerialization.isValidJSONObject(dictionary)) {
print("无法解析出JSONString")
return ""
}
let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
return JSONString! as String
}
/**
* 数组转换为JSONString
*/
class func getJSONStringFromArray(arr:Array<Any>) -> String {
if (!JSONSerialization.isValidJSONObject(arr)) {
print("无法解析出JSONString")
return ""
}
let data : NSData! = try? JSONSerialization.data(withJSONObject: arr, options: []) as NSData?
let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
return JSONString! as String
}
/**
* JSONString转换为字典
*/
class func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{
let jsonData:Data = jsonString.data(using: .utf8)!
let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
if dict != nil {
return dict as! NSDictionary
}
return NSDictionary()
}
/**
* JSONString转换为数组
*/
func getArrayFromJSONString(jsonString:String) ->NSArray{
let jsonData:Data = jsonString.data(using: .utf8)!
let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
if array != nil {
return array as! NSArray
}
return array as! NSArray
}
/// 在一定的数组中取出一个随机值()
///
/// - Returns: 随机值
class func randomValueFromIntUppercasedArr() -> String {
let arr = ["0","1","2","3","4","5","6","7","8","9","Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","M"]
let index:Int = Int(arc4random()%UInt32((arr.count - 1)))
let str = arr[index]
return str
}
}
/// 自定义Log
func HLog<T>(message : T?,file: String = #file,methodName: String = #function, lineNumber: Int = #line){
#if DEBUG
let fileName = NSString.init(string: (file as String)).lastPathComponent
let line = String.init(format: "第%d行", lineNumber)
let name = "======>"
let date = NSDate()
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "yyy-MM-dd 'at' HH:mm:ss.SSS"
let strNowTime = timeFormatter.string(from: date as Date) as String
print("[\(strNowTime)][\(fileName)\(line)]\(methodName)\(name)\(String(describing: message))")
#endif
}
网友评论