我用其他一些参数上传图像,我编写了这段代码,但是在这段代码中无法成功,我在解决此问题时遇到了一些错误
还更改参数类型(NSDictionary和字符串类型)和Alamofire更新窗格。
我面对这行错误
multipartFormData.append(value.data(using: String.Encoding.utf8)!,
withName: key)
错误是
“任何”类型的值没有成员“数据”
代码听见了
let parameter : NSDictionary = ["auth_key": UserDefaults.standard.value(forKey: GlobalConstants.kAuthKey)!,
"userid" : UserDefaults.standard.value(forKey: GlobalConstants.kuserId)!,
"eventname" : self.txtEventName.text!,
"eventdescription" : self.textviewDescription.text!,
"event_categories" : self.arrSelectEventID,
"eventshop" : self.selectedOrganizerID,
"eventreef" : self.selectedReefID,
"event_start_date_time" : self.Startdate,
"event_start_time" : self.startTime,
"event_end_date_time" : self.Enddate,
"event_end_time" : self.EnfTime,
"meeting_location" : self.MeetingPoint,
"meeting_location_address" : meetingAddress,
"meeting_location_latitude" : meetinglat,
"meeting_location_longitude" : meetingLong,
"event_ticket_price" : self.txtEventTicketPrice.text! ,
"event_ticket_qty" : self.txtEventTicketQuantity.text!,
"eventvideourl" : self.txtVideoURL.text!,
"recurrence_type" : "none" ,
"end" : self.End,
"end_type" : self.EndType,
"end-count" : self.EndCount,
"create_ticket_on_event" : ""]
let image = self.imgCover.image
let imageData = image?.jpegData(compressionQuality: 1)
Alamofire.upload(multipartFormData: { multipartFormData in
// import image to request
multipartFormData.append(imageData!, withName: "eventimage", fileName: "profile.jpg", mimeType: "image/jpeg")
for (key, value) in parameter {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to: strURL,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
}
upload.responseJSON
{ response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value
{
print("JSON: \(JSON)")
var dic = response.result.value as? [String: Any]
let alert = UIAlertController(title: "Alert", message: dic!["message"] as? String , preferredStyle: .alert)
self.present(alert, animated: true)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
}))
}
}
case .failure(let error):
print(error)
}
})`
答案 0 :(得分:-1)
我正在使用此代码,希望对您有帮助
func jsonCall(withMultipleImagesImage productImages: [UIImage]?, withfieldName strfieldName: String?, classURL urlClass: String?, witCompilation completion: @escaping (_ Dictionary: [AnyHashable: Any]?, _ error: Error?) -> Void) {
self.AddProgressHud()
//NSError *error;
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
let BoundaryConstant = "----------V2ymHFg03ehbqgZCaKO6jy"
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
let FileParamConstant = strfieldName
// the server url to which the image (or the media) is uploaded. Use your server url here
let url = URL(string: "\(urlBase)\(urlClass ?? "")")
print("url is \(String(describing: url))")
let request = NSMutableURLRequest()
// if userDefaults.value(forKey: userdefaultAuthHeader) != nil {
// //request.setValue(userDefaults.value(forKey: userdefaultAuthHeader) as? String, forHTTPHeaderField: "Authorization")
// }
request.cachePolicy = .reloadIgnoringLocalCacheData
request.httpShouldHandleCookies = false
request.httpMethod = "POST"
// set Content-Type in HTTP header
let contentType = "multipart/form-data;boundary=\(BoundaryConstant)"
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
// request.setValue(contentType, forHTTPHeaderField: "Content-Type")
// post body
let body = NSMutableData()
var count = 0
for image: UIImage in productImages!{
count += 1
let imageData = UIImage.jpegData(image)
//UIImagePNGRepresentation(image)
if imageData != nil {
if let anEncoding = "--\(BoundaryConstant)\r\n".data(using: .utf8) {
body.append(anEncoding)
}
if let anEncoding = ("Content-Disposition: form-data; name=\"\(String(describing: FileParamConstant!))\"; filename=\"image.png\"\r\n ").data(using: .utf8) {
body.append(anEncoding)
}
if let anEncoding = ("Content-Type: image/png\r\n\r\n").data(using: .utf8) {
body.append(anEncoding)
}
// if let aData = imageData {
// body.append(aData)
// }
if let anEncoding = "\r\n".data(using: .utf8) {
body.append(anEncoding)
}
}
}
if let anEncoding = "--\(BoundaryConstant)--\r\n".data(using: .utf8) {
body.append(anEncoding)
}
// setting the body of the post to the reqeust
request.httpBody = body as Data
// set the content-length
//let postLength = "\(UInt((body as Data).count))"
//request.setValue(postLength, forHTTPHeaderField: "Content-Length")
// set URL
request.url = url!
print("re url \(request.url!)")
var postDataTask: URLSessionDataTask?
postDataTask = session.dataTask(with: request as URLRequest) { data, response, error in
if error == nil {
var dicjson: [AnyHashable: Any]? = nil
DispatchQueue.main.async {
// self.hud.hide(animated: true)
}
print("\(String(data: data!, encoding: .utf8) ?? "")")
if let aData = data {
dicjson = try! JSONSerialization.jsonObject(with: aData, options: []) as? [AnyHashable: Any]
}
completion(dicjson, error)
} else {
print("erro \(String(describing: error?.localizedDescription))")
DispatchQueue.main.async {
// self.hud.hide(animated: true)
}
completion(nil, error)
//GlobalClass.showAlertwithTitle("Server Error", message: error?.description)
}
}
postDataTask?.resume()
}
如果您使用的是alammofire,请参阅this