无法使用AFNetworking上传图像



我正在使用Rubymotion创建一个iOS应用程序。我正在尝试进行分段上传的图像。

我使用此代码进行上传,但出现错误:

data = {token: "2xCGdzcuEeNzhst3Yaa8f", task: 1, message: "message", latitude: 1, longitude: 1}
    client = AFHTTPClient.alloc.initWithBaseURL(NSURL.URLWithString("http://api.example.com/api/v1/"))
        request = client.multipartFormRequestWithMethod('POST', path:"messages", parameters:data, constructingBodyWithBlock:lambda{ |form_data|
          image_data = UIImagePNGRepresentation(image.image)
          form_data.appendPartWithFileData(image_data, name:'new_avatar', fileName:'new_avatar.png', mimeType:'image/png')
        })
        operation = AFJSONRequestOperation.alloc.initWithRequest(request)
        operation.setCompletionBlockWithSuccess(lambda{ |operation, responseObject| puts 'all done!'})

我收到此错误:

undefined method `setCompletionBlockWithSuccess' for #<AFJSONRequestOperation:0xb227f00> (NoMethodError)

据我所知,操作是一个有效的对象,应该有这个方法。我在这里错过了什么吗?

更新 1

这是我更新的代码,但是当我运行它时,POST操作似乎没有触发。我是否仍然缺少任何代码?我也没有收到任何错误。

data = {token: "2xCGdzcuEeNzhs5tYaa8f", task: 1, message: "message", latitude: 1, longitude: 1}
    client = AFHTTPClient.alloc.initWithBaseURL(NSURL.URLWithString("http://api.example.com/api/v1/"))
    request = client.multipartFormRequestWithMethod('POST', path:"messages", parameters:data, constructingBodyWithBlock:lambda{ |form_data|
      image_data = UIImagePNGRepresentation(image.image)
      form_data.appendPartWithFileData(image_data, name:'new_avatar', fileName:'new_avatar.png', mimeType:'image/png')
    })
    operation = AFJSONRequestOperation.alloc.initWithRequest(request)
    operation.setCompletionBlockWithSuccess(lambda { |operation, responseObject| puts 'all done!'},
                                            failure: lambda { |operation, error| puts 'error' })

请求对象输出以下内容:

<NSMutableURLRequest:195641792 - url: http://api.example.com/api/v1/messages, 
    headers: {"Content-Length"=>"118200", "Content-Type"=>"multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY", "Accept-Language"=>"en, fr, de, ja, nl, it, es, pt, pt-PT, da, fi, nb, sv, ko, zh-Hans, zh-Hant, ru, pl, tr, uk, ar, hr, cs, el, he, ro, sk, th, id, ms, en-GB, ca, hu, vi, en-us;q=0.8", "User-Agent"=>"theapp/1.0 (iPhone Simulator; iOS 6.0; Scale/1.00)"}, 
    cache policy: 0, Pipelining: false, main doc url: ,    timeout: 60.0, network service type: 0 >

操作对象输出以下内容:

<AFJSONRequestOperation:0xa78c660>

方法签名setCompletionBlockWithSuccess(lambda..., failure: lambda...) -- 您需要添加一个失败参数。像这样:

operation.setCompletionBlockWithSuccess(lambda { |operation, responseObject| puts 'all done!'},
                                        failure: lambda { |operation, error| puts 'error' })

此外,还需要确保实际启动请求操作:

operation.start

有关此方法的定义,请参阅 https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFJSONRequestOperation.m#L102-L103。

我写了一个类来做这种工作。 在这里查看我的答案。 它使用 AFNetworking,并包括用于基本网络请求的方法。

最新更新