错误:“模式无法匹配‘URLRequest’类型的值";迅速 [英] Error: "Pattern cannot match values of type 'URLRequest'" in swift

查看:20
本文介绍了错误:“模式无法匹配‘URLRequest’类型的值";迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码之前运行良好..最近我在其他项目中安装了 Alamofire 现在低于错误抛出.

My code was working perfectly in before.. recently i have installed Alamofire in other project now below error throwing.

模式不能匹配URLRequest"类型的值

在 Alamofire 中的这一行出现错误:

case .Success(let upload, _, _): \\........这里出现错误

错误代码:

 func postImageRequestWithURL(withUrl strURL: String,withParam postParam: Dictionary<String, Any>,withImages imageArray:NSMutableArray,completion:@escaping (_ isSuccess: Bool, _ response:NSDictionary) -> Void) {

        AF.upload(multipartFormData: { (MultipartFormData) in
        // Here is your Image Array
        for (imageDic) in imageArray {
            let imageDic = imageDic as! NSDictionary
            for (key,valus) in imageDic {
                MultipartFormData.append(valus as! Data, withName:key as! String,fileName: "file.jpg", mimeType: "image/jpg")
            }
        }
            
        for (key, value) in postParam {
            MultipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }
    }, to: strURL, usingThreshold: UInt64.init(), method: .post, headers:["userId":"mfjeriefei","key":"cnhsdnchsj"]) {(result) in
        switch result {
        case .Success(let upload, _, _): \\........here getting error
            upload.uploadProgress(closure: {(progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })
            upload.responseJSON { response in
                if response.response?.statusCode == 200 {
                    let json = response.result.value as? NSDictionary
                    completion(true,json!);
                }
                else {
                    let json = response.result.value as? NSDictionary
                    completion(false,json!);
                }
            }
        case .failure(let encodingError):\\ ............here getting error
            print(encodingError)
            completion(false,[:]);
        }
    }
}
}

就像下面我调用的方法:

func addNewEvents() {
    var ImageArray : NSMutableArray!
    
    let data = ["eventName":"Abhi's Birthday", "eventMessage":"Please come and join us", "eventDate":"15-07-2020", "eventTime":"11:30AM"] as [String : Any]

    do {
        let json = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
        let myJsonString  = NSString(data: json, encoding: String.Encoding.utf8.rawValue)! as String
        let parameters : [String:String] = ["eventdetails":myJsonString]
        
        print("event add json \(json)")
      
        guard let imageData = pickedImage?.pngData() else { return }
        let ImageDic  = ["eventImage" : imageData]
        ImageArray    = NSMutableArray(array: [ImageDic as NSDictionary])
        postImageRequestWithURL(withUrl: "http://hbfbfhjdbfj/create/event/", withParam: parameters, withImages: ImageArray) { (isSuccess, response) in
            if isSuccess {
                print(response)
            } else {
                print(response)
            }
        }
    } catch {
        print("error")
    }
}

 eventdetails: ["eventName":"Abhi's Birthday", "eventMessage":"Please come and join us", "eventDate":"21-07-2020", "eventTime":"11:30AM", "eventEndDate":"21-07-2020", "eventEndTime":"11:00PM", "isAllDayEvent":"false", "isEventRepeatable":"false", "eventAddress":"123 Hyd Rd", "eventCity":"Secbad", "location":["latitude":"-23.345","longitude":"15.234"], "remindersList":["1-day","1-hours"], "eventFrequency":"Never", "numberOfOccurrences":"", "showGuests":true, "status":"Draft", "createGroup":"true", "inviteeType":"individuals",  "groupId":"", "guestList":[["userKey":"ef54983685274366ba339375ecda69df"], ["phoneNumber":"3106198542"], ["phoneNumber":"8188369592"]]] as [String : Any]

邮递员输出:

我无法解决上述错误..请任何人帮助我解决更新代码中的错误

I am unable to solve the above error.. please any one help m e to solve the error in updated code

推荐答案

你可以用最新的 alamofire 试试下面的代码.

You can try the below code with latest alamofire.

  func addNewEvents()
    {
        let dict = ["eventName":"Abhi's Birthday", "eventMessage":"Please come and join us", "eventDate":"21-07-2020", "eventTime":"11:30AM", "eventEndDate":"21-07-2020", "eventEndTime":"11:00PM", "isAllDayEvent":"false", "isEventRepeatable":"false", "eventAddress":"123 Hyd Rd", "eventCity":"Secbad", "location":["latitude":"-23.345","longitude":"15.234"], "remindersList":["1-day","1-hours"], "eventFrequency":"Never", "numberOfOccurrences":"", "showGuests":true, "status":"Draft", "createGroup":"true", "inviteeType":"individuals",  "groupId":"", "guestList":[["userKey":"ef54983685274366ba339375ecda69df"], ["phoneNumber":"3106198542"], ["phoneNumber":"8188369592"]]] as [String : Any]

        let pickedImage : UIImage = UIImage.init(named: "ic_sample.png")!
        self.postComplexPictures(url:NSURL.init(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/create/event/")! as URL , params: dict, imageToUpload: pickedImage) { (arg0) in
            let (_, list, isSuccess) = arg0
            if(isSuccess)
            {
                print(list)
            }
            else{
                print(list)
            }
        }
    }

这里是上传方法:

 func postComplexPictures(url:URL, params:[String:Any], imageToUpload : UIImage, finish: @escaping ((message:String, list:[[String: Any]],isSuccess:Bool)) -> Void)
    {
        var result:(message:String, list:[[String: Any]],isSuccess:Bool) = (message: "Fail", list:[],isSuccess : false)

        let headers: HTTPHeaders
        headers = ["deviceid": "F139424D-C749-42F6-B804-21BD17E28CE0","userType": "personal","key": "c913136e897b419bab20746de7baab62", "Content-Type":"application/json"]

        AF.upload(multipartFormData: { (multipartFormData) in
            let jpegData = imageToUpload.jpegData(compressionQuality: 0.5)
            let jsonData = try! JSONSerialization.data(withJSONObject: params, options: [])
            multipartFormData.append(jsonData, withName: "eventdetails" )
            multipartFormData.append(jpegData!, withName: "eventImage",fileName: "file.jpg", mimeType: "image/jpg")
        }, to: url, usingThreshold: UInt64.init(), method: .post, headers: headers).response{ response in

            if((response.error == nil))
           {
                do
                {
                    if let jsonData = response.data
                    {
                        let parsedData = try JSONSerialization.jsonObject(with: jsonData) as! Dictionary<String, AnyObject>

                        let status = parsedData["status"] as? NSInteger ?? 0
                        let msg = parsedData["message"] as? String ?? ""

                        print("parsedData=", parsedData)
                        
                        if(status==1) {
                            result.isSuccess = true
                            result.message=msg
                            if let jsonArray = parsedData["data"] as? [[String: Any]] {
                                result.list=jsonArray
                            }
                        } else {
                            result.isSuccess = false
                            result.message=msg
                        }

                    }
                    finish(result)
                } catch {
                   finish(result)
                }
            } else {
                print("Resonse.error",response.error?.localizedDescription as Any)
                finish(result)
            }
        }
    }

请根据您的方便处理回复.

Please handle the response as per your convenience.

这篇关于错误:“模式无法匹配‘URLRequest’类型的值";迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆