错误:“模式无法匹配 'URLRequest' 类型的值”在 swift 中

Posted

技术标签:

【中文标题】错误:“模式无法匹配 \'URLRequest\' 类型的值”在 swift 中【英文标题】:Error: "Pattern cannot match values of type 'URLRequest'" in swift错误:“模式无法匹配 'URLRequest' 类型的值”在 swift 中 【发布时间】:2020-07-19 05:26:27 【问题描述】:

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

Pattern cannot match values of type 'URLRequest'

Alamofire 在这一行出现错误:

case .Success(let upload, _, _): \\........here getting 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,[:]);
        
    


如下所示,我正在调用该方法:

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]

邮递员 ouypot:

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

【问题讨论】:

【参考方案1】:

您可以使用最新的 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)
            
        
    

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

【讨论】:

你好..您的代码看起来可以工作..但我无法使用它..我也用 JSON 相关代码更新了我的帖子..你能根据我的帖子帮助我编写代码吗 当然让我再检查一遍 这里我也无法使用result @swiftDev 我已经更新了答案。请检查并告诉我它是否适合您。 在这里我可以知道我在哪里得到我的 json 响应【参考方案2】:

错误与一个小错误有关(即根据Alomofire的.success语法,并将AF更改为Alamofire),我已经更正了语法和代码。现在你可以使用如下:-

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

【讨论】:

以上是关于错误:“模式无法匹配 'URLRequest' 类型的值”在 swift 中的主要内容,如果未能解决你的问题,请参考以下文章

Informix 错误:发生了语法错误。错误代码:-201

我收到一个错误:“MetaMask - RPC 错误:错误:错误:[ethjs-rpc] rpc 错误与有效负载”

错误精灵错误跟踪器错误

网页打开显示错误500是啥意思

PHP错误处理

PHP的错误处理