如何将Int值添加到Alamofire上传参数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将Int值添加到Alamofire上传参数相关的知识,希望对你有一定的参考价值。
我想将Int
值添加到multipartFormData
:
Alamofire.upload(.POST,
url,
headers: headers,
multipartFormData: { multipartFormData in
//add some jpg image
//add other vaues:
for (key, value) in parameters {
if value is String {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
} else if value is Int {
let convertedValueNumber: NSNumber = NSNumber(int: value.intValue)
let data = NSKeyedArchiver.archivedDataWithRootObject(convertedValueNumber)
multipartFormData.appendBodyPart(data: data, name: key)
}
}
}, encodingCompletion: { encodingResult in
//some processing
})
但服务器返回错误,我不发送Int
值。如何将Int
值添加到参数中?
答案
NSKeyedArchiver
非常好奇。通常你只是发送字符串表示,例如:
Alamofire.upload(.POST, URL, headers: headers, multipartFormData: { multipartFormData in
//add some jpg image
//add other values:
for (key, value) in parameters {
if value is String {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
} else if value is Int {
multipartFormData.appendBodyPart(data: "(value)".dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}
}, encodingCompletion: { encodingResult in
//some processing
})
或者,甚至更简单,因为字符串插值适用于String
和Int
:
Alamofire.upload(.POST, URL, headers: headers, multipartFormData: { multipartFormData in
//add some jpg image
//add other values:
for (key, value) in parameters {
if value is String || value is Int {
multipartFormData.appendBodyPart(data: "(value)".dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}
}, encodingCompletion: { encodingResult in
//some processing
})
或者,在Alamofire 4中使用Swift 3:
Alamofire.upload(multipartFormData: { multipartFormData in
//add some jpg image
//add other values:
for (key, value) in parameters {
if value is String || value is Int {
multipartFormData.append("(value)".data(using: .utf8)!, withName: key)
}
}
}, to: url, method: .post, headers: headers, encodingCompletion: { encodingResult in
//some processing
})
以上是关于如何将Int值添加到Alamofire上传参数的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Alamofire 4.0 中添加带有上传进度百分比的标签的进度条
如何在 Swift 中使用 Alamofire 上传带有 JSON 参数的图像?
如何在 Swift 4 中使用 Alamofire 上传具有其他参数的多个图像