You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中Alamofire报错:Pattern cannot match values of type 'URLRequest'

解决Alamofire升级后上传请求的Pattern匹配错误

兄弟,这问题百分百是Alamofire版本升级搞的鬼!你之前的代码是旧版Alamofire(大概率是4.x)的写法,而新版本(5.x+)的AF.upload API已经完全重构了——不再返回带.success/.failure的枚举,直接返回UploadRequest实例,所以原来的switch分支自然匹配不上URLRequest类型,就报那个"Pattern cannot match values of type 'URLRequest'"错误了。

下面给你把代码改成适配新版Alamofire的写法:

一、重构上传方法核心逻辑

把原来的AF.upload回调部分完全换掉,新版不需要那个结果枚举的switch,直接拿到UploadRequest后处理进度和响应即可:

func postImageRequestWithURL(withUrl strURL: String, withParam postParam: Dictionary<String, Any>, withImages imageArray: NSMutableArray, completion:@escaping (_ isSuccess: Bool, _ response: NSDictionary) -> Void) {
    // 新版AF.upload直接返回UploadRequest实例
    let uploadRequest = AF.upload(multipartFormData: { multipartFormData in
        // 处理图片数组,增加安全校验避免崩溃
        for imageDic in imageArray {
            guard let imageDict = imageDic as? NSDictionary else { continue }
            for (key, value) in imageDict {
                guard let imageData = value as? Data, let fieldName = key as? String else { continue }
                multipartFormData.append(imageData, withName: fieldName, fileName: "file.jpg", mimeType: "image/jpg")
            }
        }
        // 处理普通参数,同样增加安全校验
        for (key, value) in postParam {
            guard let stringValue = value as? String, let data = stringValue.data(using: .utf8) else { continue }
            multipartFormData.append(data, withName: key)
        }
    }, to: strURL, method: .post, headers: ["userId":"mfjeriefei","key":"cnhsdnchsj"])
    
    // 监听上传进度
    uploadRequest.uploadProgress { progress in
        print("Upload Progress: \(progress.fractionCompleted)")
    }
    
    // 处理响应结果
    uploadRequest.responseJSON { response in
        switch response.result {
        case .success(let json):
            completion(true, json as? NSDictionary ?? [:])
        case .failure(let error):
            print("上传错误:\(error.localizedDescription)")
            completion(false, [:])
        }
    }
}

二、适配更新后的eventdetails参数

你的新eventdetails是复杂嵌套字典,确保JSON序列化过程安全即可,调用方法可以优化成这样:

func addNewEvents() {
    var imageArray: NSMutableArray!
    // 更新后的eventdetails参数
    let 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]
    
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: eventDetails, options: [])
        guard let jsonString = String(data: jsonData, encoding: .utf8) else {
            print("JSON转字符串失败")
            return
        }
        let parameters: [String: String] = ["eventdetails": jsonString]
        
        // 图片数据安全校验
        guard let pickedImage = pickedImage, let imageData = pickedImage.pngData() else {
            print("图片数据为空")
            return
        }
        let imageDict = ["eventImage": imageData] as NSDictionary
        imageArray = NSMutableArray(array: [imageDict])
        
        // 调用上传方法
        postImageRequestWithURL(withUrl: "http://hbfbfhjdbfj/create/event/", withParam: parameters, withImages: imageArray) { (isSuccess, response) in
            print(isSuccess ? "请求成功:\(response)" : "请求失败:\(response)")
        }
    } catch {
        print("JSON序列化错误:\(error)")
    }
}

三、额外提醒

  • 确认你的Alamofire版本是5.x+,如果用CocoaPods,Podfile里应该写pod 'Alamofire', '~> 5.0'
  • 尽量少用NSMutableArray、NSDictionary这类OC容器,换成Swift原生的[[String: Any]]、[String: Any]会更安全
  • 避免用as!强制转换,多用as?可选绑定,减少运行时崩溃风险

内容的提问来源于stack exchange,提问作者Swift

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 15:27:42