Json 错误:";模式无法与类型为';URL请求'&引用;迅速地
我的代码以前在中工作得很好。。最近我在下面的其他项目中安装了Json 错误:";模式无法与类型为';URL请求'&引用;迅速地,json,swift,alamofire,Json,Swift,Alamofire,我的代码以前在中工作得很好。。最近我在下面的其他项目中安装了Alamofire 模式无法匹配“URLRequest”类型的值。 在Alamofire中的此行中出错: func postImageRequestWithURL(withUrl strURL: String,withParam postParam: Dictionary<String, Any>,withImages imageArray:NSMutableArray,completion:@escaping (_ is
Alamofire
模式无法匹配“URLRequest”类型的值。
在Alamofire中的此行中出错:
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]
case.Success(让我们上传,\,\:\ \……这里是获取错误的地方
出现错误的代码:
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]
编辑:
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]
邮递员奥波特:
我无法解决上述错误。。请任何人帮助ME解决更新代码中的错误错误与一个小错误有关(即根据Alomofire成功语法,并将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,[:]);
}
}
}
func postmagerequestwithurl(withUrl strURL:String,withParam postParam:Dictionary,withImages imageArray:NSMutableArray,completion:@escaping(u-issucess:Bool,uu-response:NSDictionary)->Void){
上传(multipartFormData:{(multipartFormData)在
//这是您的图像阵列
用于imageArray中的(imageDic){
设imageDic=imageDic as!NSDictionary
用于imageDic中的(键、值){
MultipartFormData.append(值为!Data,名称为:key as!String,文件名:“file.jpg”,mimeType:“image/jpg”)
}
}
用于后置参数中的(键、值){
MultipartFormData.append((值为AnyObject).data(使用:String.Encoding.utf8.rawValue)!,with name:key)
}
},使用reshold:UInt64.init(),to:strURL,方法:.post,标题:[“userId”:“mfjeriefei”,“key”:“cnhsdnchsj”]){(结果)在
切换结果{
case.success(让我们上传,,,):/…这里有错误
uploadProgress(闭包:{(进度)在
打印(“上载进度:\(Progress.fractionCompleted)”)
})
upload.responseJSON{中的响应
如果响应.response?.statusCode==200{
将json=response.result.value设为?NSDictionary
完成(true,json!);
}
否则{
将json=response.result.value设为?NSDictionary
完成(false,json!);
}
}
case.failure(let encodingError)://………此处获取错误
打印(编码错误)
完成(假,[:]);
}
}
}
错误与一个小错误有关(即根据Alomofire成功语法,并将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,[:]);
}
}
}
func postmagerequestwithurl(withUrl strURL:String,withParam postParam:Dictionary,withImages imageArray:NSMutableArray,completion:@escaping(u-issucess:Bool,uu-response:NSDictionary)->Void){
上传(multipartFormData:{(multipartFormData)在
//这是您的图像阵列
用于imageArray中的(imageDic){
设imageDic=imageDic as!NSDictionary
用于imageDic中的(键、值){
MultipartFormData.append(值为!Data,名称为:key as!String,文件名:“file.jpg”,mimeType:“image/jpg”)
}
}
用于后置参数中的(键、值){
MultipartFormData.append((值为AnyObject).data(使用:String.Encoding.utf8.rawValue)!,with name:key)
}
},使用reshold:UInt64.init(),to:strURL,方法:.post,标题:[“userId”:“mfjeriefei”,“key”:“cnhsdnchsj”]){(结果)在
切换结果{
case.success(让我们上传,,,):/…这里有错误
uploadProgress(闭包:{(进度)在
打印(“上载进度:\(Progress.fractionCompleted)”)
})
upload.responseJSON{中的响应
如果响应.response?.statusCode==200{
将json=response.result.value设为?NSDictionary
完成(true,json!);
}
否则{
将json=response.result.value设为?NSDictionary
完成(false,json!);
}
}
case.failure(let encodingError)://………此处获取错误
打印(编码错误)
完成(假,[:]);
}
}
}
您可以使用最新的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)
}
}
}
func postComplexPictures(url:url,参数:[String:Any],imageToUpload:UIImage,finish:@escaping((消息:String,列表:[[String:Any]],isSuccess:Bool))->Void)
{
var结果:(消息:字符串,列表:[[String:Any]],isSuccess:Bool)=(消息:“Fail”,列表:[],isSuccess:false)
let头文件:HTTPHeaders
标题=[“设备ID”:“F139424D-C749-42F6-B804-21BD17E28CE0”,“用户类型”:“个人”,“密钥”:“c913136e897b419bab20746de7baab62”,“内容类型”:“应用程序/json”]
AF.upload(multipartFormData:{(multipartFormData)在
设jpegData=imageToUpload.jpegData(压缩质量:0.5)
让jsonData=try!JSONSerialization.data(使用jsonObject:params,选项:[])
multipartFormData.append(jsonData,名称为:“eventdetails”)
multipartFormData.append(jpegData!,名称为:“eventImage”,文件名为:“file.jpg”,mimeType:“image/jpg”)
},收件人:url,使用reshold:UInt64.init(),方法:.post,头:headers)。响应{response in
如果((response.error==nil))
{
做
{
如果让jsonData=response.data
{
让parsedData=try JSONSerialization.jsonObject(with:jsonData)作为!字典