无法在 Alamofire 多格式数据请求中发送字典数组

Posted

技术标签:

【中文标题】无法在 Alamofire 多格式数据请求中发送字典数组【英文标题】:Unable to send Array of Dictionary in Alamofire multiform data Request 【发布时间】:2022-01-06 15:21:34 【问题描述】:

我正在尝试在 alamofile Multiform 数据中发送带有图像的字典数组。但它返回错误 期望字典,但得到了 str for product_review_skin_concerns

代码如下:

    func uploadReviewFiles(method:HTTPMethod,imagesData:[Data],imageKey:String,parm:Parameters,header:HTTPHeaders,url:String,comp:@escaping(Result<Data,AFError>)->Void)
    AF.upload(multipartFormData:  (multipartFormData) in
        for data in imagesData
            multipartFormData.append(data, withName: imageKey, fileName: "\(Date().timeIntervalSince1970).png", mimeType: "image/png")
        
        
        
        for (key, value) in parm 
            if  key == "product_review_skin_concerns"
                guard let arr = value as? [[String:Any]] elsereturn
                for val in arr
                   
                    multipartFormData.append("\(val)".data(using: String.Encoding.utf8)!, withName: key)
                
                
            else
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)
            
            
            
           
            
        
        
    , to: url,method: method,headers: header).validate(statusCode: 200..<299).responseData  (data) in
        switch data.result
        case .success(let recivedData):
            print(NSString(data: recivedData, encoding: String.Encoding.utf8.rawValue) ?? "Unable to pring string value of data")
            comp(.success(recivedData))
            
        case .failure(let error):
            comp(.failure(error))
            print(error)
            print(error.localizedDescription)
            
        
    
    

这是我用图片发布的 parm 参数

["cons": "Test Review", "product": "9a66dc08-a54f-4af4-928c-14e760af9e8e", "rate": 3, "pros": "Test Review", "product_review_skin_concerns": [["skin_concern": "a2d92030-93f3-4c71-a834-1a6a1b937183", "percent": 0], ["percent": 0, "skin_concern": "8ea0ab47-1c1a-4a78-ae62-91da250a09c9"], ["skin_concern": "717811f1-0a87-4ed0-8561-5c8a10c3968c", "percent": 0]]]

【问题讨论】:

您只是附加了字典的插值字符串描述。它可能需要某种特定格式,因此您需要弄清楚该格式是什么,并在上传期间将字典值转换为该格式。 @JonShier 我在邮递员中发送相同的参数,不知何故它与邮递员一起工作。 Postman 似乎正在为您编码字典,因此您需要弄清楚该编码是什么并在此处应用它。 【参考方案1】:

初始化变量

var invitationsArray = Array<[String: Any]>()
var invitations = Array<[String: Any]>()

逻辑

    invitations = [["friend_id": "\(each.friendId!)", "invited_type": "friend"]]
                    invitationsArray.append(contentsOf: invitations)

设置变量

let params: [String: Any] = [
            "user_id":Global.shared.currentUserLogin.id,
            "ride_name": planARide.name!,
            "ride_description": planARide.description!,
            "ride_type": planARide.rideType!,
            "ride_date_and_time": planARide.rideDate!,
            "ride_city": planARide.city!,
            "ride_meeting_spot": planARide.rideMeetingSpot!,
            "ride_meeting_latitude": planARide.latitude!,
            "ride_meeting_longitude": planARide.longitude!,
            "ride_intensity": planARide.rideIntensity!,
            "time_length_of_ride": planARide.rideTime!,
            "reoccuring_ride": planARide.rideReccurring!,
            "special_instructions": planARide.specialInstruction!,
            "open_ride_to_biking_community": planARide.openRideToBikingCommunity!,
            "invitations": invitationsArray
        ]

这样的 AF 请求

func requestWithHeaderandBody(vc:UIViewController , url:String , params:[String:Any] , method:HTTPMethod = .post, type:String = "", loading:Bool = true)
        
        let loaderVC : LoaderViewController =  UIStoryboard.controller()
        
        if CheckInternet.Connection()
            if loading
                            
                loaderVC.modalPresentationStyle = .overCurrentContext
                vc.present((loaderVC), animated: false, completion: nil)
            
            
            AF.request( Apis.baseURL + url , method: method, parameters: params , encoding: URLEncoding.default, headers: headers).responseJSON  (response) in
                
                switch response.result
                
                case .success(let value):

                    
                    let json = JSON(value)
                    let status = json["status"].stringValue
                    let message = json["message"].stringValue
                    if status == "200"
                        print("Sucessfully APi Hit")
                        if let del = self.delegate
                            loaderVC.dismiss(animated: false, completion: nil)
                            del.onSuccess(json: json, val: type)
                        
                    else if status == "400"
                        loaderVC.dismiss(animated: false, completion: nil)

                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) 

                            vc.showAlertWithOk(withTitle: Alert.String.alert, withMessage: json["message"].stringValue)
                        
                        
                    
                    

                
                case .failure(let err):
                    err.localizedDescription
                    loaderVC.dismiss(animated: false, completion: nil)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) 
                        vc.showAlertWithOk(withTitle: Alert.String.alert, withMessage: "Service Failure \(err.localizedDescription)")
                    
                    break
                
            
        else
            print("No internet connection")
        
    

【讨论】:

以上是关于无法在 Alamofire 多格式数据请求中发送字典数组的主要内容,如果未能解决你的问题,请参考以下文章

Alamofire 4.3 无法发送 JSON 请求

用 alamofire 快速发送获取请求

Alamofire 多个请求

在 swift 中使用 alamofire 发送 JSON 数组作为参数

Swift - 使用 alamofire 发布请求

发送请求时从数据库中删除 Swift Alamofire“+”号