Wednesday, 15 April 2015

ios - AFNetworking: Send image from file -



ios - AFNetworking: Send image from file -

i trying send multi-part post request includes image. next code works fine:

manager.post( apiurl + "/location/add", parameters: parameters, constructingbodywithblock: { (formdata : afmultipartformdata!) -> void in // formdata.appendpartwithfileurl(nsurl(string: location.imagepath!), name: "image", error: nil)}, formdata.appendpartwithfiledata(img, name: imgparam, filename: "randomimagename.jpg", mimetype: "image/jpeg")}, success: { (operation: afhttprequestoperation!,responseobject: anyobject!) in println("json: " + responseobject.description) var dict = responseobject nsdictionary allow json = jsonvalue(dict) var message = "" if allow msg = json["message"].string {message = msg} var success = false if allow s = json["success"].bool { callback(success: success, msg: message) } }, failure: { (operation: afhttprequestoperation!,error: nserror!) in println("error: " + error.localizeddescription) var apierror = apierror() apierror.noconnection = true errorcallback(apierror: apierror) })

i want utilize appendpartwithfileurl instead of appendpartwithfiledata. if replace 5th line wiht line commented out in code above, next compiler error:

extra argument 'constructingbodywithblock' in phone call

does know how resolve this?

edit: found (very, very, strange) solution. replace line

formdata.appendpartwithfileurl(nsurl(string: location.imagepath!), name: "image", error: nil)},

with

var temp = formdata.appendpartwithfileurl(nsurl(string: location.imagepath!), name: "image", error: nil)},

i didn't alter beside adding var temp =. have no thought why working, does. seems unusual bug.

if haven't solved problem yet, seek casting location.imagepath string.

i had same problem till i've added as string in next code:

func uploadfile(file: nsdata, url: string, formdata: nsdictionary, parameters: nsdictionary, completion: anyobject -> void, failure: nserror -> void) { operationmanager.requestserializer = afjsonrequestserializer() afhttprequestserializer if operationmanager.reachabilitymanager.networkreachabilitystatus != .notreachable { operationmanager.post(url, parameters: parameters, constructingbodywithblock: { (data) in data.appendpartwithfiledata(file, name: formdata["filename"] string, filename: formdata["filename"] string, mimetype: formdata["mimetype"] string) }, success: { (operation, responseobject) in completion(responseobject) }, failure: { (operation, error) in failure(error) }) } else { showreachabilityalert() } }

hope helps.

ios swift afnetworking-2

No comments:

Post a Comment