0

我正在使用 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>
4

2 回答 2

1

方法签名是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 。

于 2012-12-12T23:44:26.393 回答
0

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

于 2012-12-12T18:45:18.363 回答