Search code examples
iosswiftafnetworking-2swift2

Posting image with Swift 2 + AFNetworking


I have the following code

let manager = AFHTTPRequestOperationManager()
    manager.POST(
        "http://shipeala.redmintlabs.com/api/orders/create",
        parameters: params,
        constructingBodyWithBlock: { (formData : AFMultipartFormData!) -> Void in
            formData.appendPartWithFileData(SHOrderImage.getInstance().image!, name: "photo", fileName: "image.jpg", mimeType: "image/*")
        },
        success: { (operation: AFHTTPRequestOperation!,
            ""
        },
        failure: { (operation: AFHTTPRequestOperation!,
            error: NSError!) -> Void in
            ""
        }
    )

And i got this error:

Cannot invoke 'POST' with an argument list of type '(String, parameters: NSDictionary, constructingBodyWithBlock: (AFMultipartFormData!) -> Void, success: (AFHTTPRequestOperation!, AnyObject!) -> Void, failure: (AFHTTPRequestOperation!, NSError!) -> Void)'

Any ideas??


Solution

  • // add this line of code for image to NSData conversion
    let imageData = UIImageJPEGRepresentation(UIImage(named: "yourImageNAme"), 0.5)
    
    
    let op : AFHTTPRequestOperation = manager.POST("", parameters: parameters, constructingBodyWithBlock: { (formData: AFMultipartFormData!) -> Void in
                formData.appendPartWithFileData(imageData!, name: "Photo", fileName: "photo.jpg", mimeType: "image/jpeg")
                },
                success:
                {
                    (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
    
                       print(responseObject)                 
    
                },
                failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
                    print(error)
    
            })!
    
    
    op.start()