Error: “Pattern cannot match values of type 'URLRequest'” in swift

旧街凉风 提交于 2021-02-05 11:38:23

问题


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

Pattern cannot match values of type 'URLRequest'

got error in Alamofire in this line:

case .Success(let upload, _, _): \\........here getting error

code with error:

 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,[:]);
        }
    }
}
}

like below i am calling the method:

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")
    }
}

EDIT:

 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]

the postman ouypot:

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


回答1:


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)
            }
        }
    }

And here is the uploading method:

 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.




回答2:


Error is related to a small mistake(i.e .success syntax according to Alomofire, and change AF as Alamofire), I have correct the Syntax as well as code. Now you can use as follows:-

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

          Alamofire.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)
          }
          }, usingThreshold: UInt64.init(), to: strURL, 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,[:]);
          }
      }
  }


来源:https://stackoverflow.com/questions/62976628/error-pattern-cannot-match-values-of-type-urlrequest-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!