Coder Social home page Coder Social logo

afmotion's People

Contributors

andrewhavens avatar averethel avatar ben5516 avatar chrisradford avatar clayallsopp avatar cyberfox avatar durnin avatar gantman avatar iwarshak avatar jbender avatar joshsmith avatar markrickert avatar rromanchuk avatar sajoku avatar travisvalentine avatar xizhao avatar zmillman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

afmotion's Issues

not working

trying to compile the AppDotNet example i have this error:

AppDotNet[10490:c07] http_client.rb:62:in build:': undefined methodclientWithBaseURL' for AFHTTPClient:Class (NoMethodError)

AFMotion::SessionClient doesn't provide access to body on error

My api server returns an errors JSON response when a record can't be saved. When using the SessionClient setup on iOS7, I can't access the body of the response -- it gives a "Cannot call result.body of a task (RuntimeError)" exception.

If I use AFMotion::Client instead, it works fine.

client = AFMotion::SessionClient.build("http://example.com") do
  session_configuration :default
  header "Accept", "application/json"
  response_serializer :json
end

client.post("api/v1/notes", note: {foo: "bar"}) do |result|
  if result.failure?
    # Raises exception: "Cannot call result.body of a task (RuntimeError)"
    NSLog "Errors: %@", result.body
  end
end

How to get JSON object during error?

On the server I am sending a json error (not 200 OK) object from my rails app, say something like this -

render json: { errors: ["User not found"] }, status: :not_found

JSON response:

{
  "errors": ["User not found"]
}

Inside my iOS app, how do I get access to error object on - failure? since result.object does not return error JSON object, its returns nil

http_client(:host_url).post(URL_AUTH_SIGNIN, auth: data) do |result|
  @response = result.object

  if result.success?
    handle_login_success(@response)
  else
    # @response in nil here??
    handle_server_error(@response)
  end
end

def http_client(type = :api_url)
  url = type == :api_url ? URL_BASE : URL_HOST

  AFMotion::SessionClient.build(url) do
    session_configuration :default
    all_headers.each { |key, value| header(key, value) }
    response_serializer :json
  end
end

Set accepted header types

How would you go about this in afmotion?

I'm querying for a plist like this:

  AFMotion::PLIST.get("http://#{@signup_input.text}.uninkd.com/existence.plist") do |result|
    if result.success?
      ap "Success"
    elsif result.failure?
      ap "result.failure"
    end
  end

It's being returned as a failure all the time though, since it's not a "application/x-plist" on the server, but a "text/plist".

How can I set the accepted headers on the request?

Wrong MIME type being sent to server

I have a server that accepts POST request on /user/signup and accepts JSON data as body.

The API works fine when I test it from Postman chrome extension with details:

URL: http://localhost:9000/user/signup
Content-Type: application/json
JSON: {"username": "test3","password": "something"}

However, when I try to do this from AFMotion I get a 415 (Unsupported Media Type) error on the server side. This is what I'm doing:

  client = AFMotion::SessionClient.build("http://localhost:9000/") do
    session_configuration :default
    header "Accept", "application/json"
    header "Content-Type", "application/json"
    response_serializer :json
  end

  puts "This is conent-type: " + client.headers["Content-Type"]
  puts "This is accept: " + client.headers["Accept"]

  client.post("user/signup", username: "token1", password: "something") do |result|
    puts result.to_string
  end

In order to debug I'm outputting the Content-Type of the request received by the server and it seems to be application/x-www-form-urlencoded; charset=utf-8 rather than application/json as I specified in my code.

What am I doing wrong?

Typo in Readme

Hello,

In the readme example for multipart upload this is wrong:

my_widget.update_progress(progress)

I had to change to:

my_widget.setProgress(progress)

Trouble with 401 response when using AFNetworking v1.2.1.

I'm making a simple JSON.get request against a https endpoint. When the endpoint returns a 401 response it never enters the callback.

This happens only when using AFNetworking v1.2.1 and not when using AFNetworking 1.2.0.

Is this a known issue? Please let me know if you need any more info.

clarify how to specify JSON for APIs

This may just be a documentation request & I can submit a PR once I understand this correctly.

For repeated accesses, the doc recommends

client = AFMotion::Client.build("https://alpha-api.app.net/") do
  header "Accept", "application/json"
  operation :json
end

But later it says that parameter_encoding is needed to specify that outbound params should be encoded with JSON, and I found it necessary to get my app working (JSON formatting required in both directions). The Accept header specifies the format of the response. What exactly does operation :json do?

What am I missing about the way AFMotion invokes its block on completion of a web request

I've been doing some work trying to integrate @seanlilmateus Futuristic gem with AFMotion so that I can use futures to work with web requests instead of having to run multiple web requests inside nested blocks. However, I'm coming unstuck because of the way that AFMotion calls back its block when its web request is finished. For a reason that escapes me, the block is not invoked until after anything to do with either semaphores or Dispatch::Future from the Futuristic gem has finished.

So either I'm doing something crazy (entirely possible!) or there's something odd about the way AFMotion calls back it's block that is incompatible with either semaphores or futures (at least as I am using them here).

I've created a standalone test class that runs through four tests:

  1. test_make_sync: this uses the pattern described above in this thread to wait on a block. This works as expected.
  2. test_futurise: this uses the pattern described in @seanlilmateus Futuristic gem, and also works as I would expect it to.
  3. test_afmotion_using_semaphores: this test attempts to use the semaphore pattern from #1 to wait on execution of a call to AFMotion:HTTP.get. It doesn't work.
  4. test_afmotion_using_futures: this test attempts to use the future pattern from #2 to wait on execution of a call to AFMotion:HTTP.get. It doesn't work either.

The test can be invoked from the REPL via: Futuriser::Tester.test

If I run the test, I see that while #1 and #2 work according to plan, both #3 and #4 timeout before a result is returned. And in both #3 and #4, the block passed into the AFMotion::HTTP.get call is not invoked until well after everything else finishes. If I invoke Futuriser::Tester.test from the RubyMotion REPL, then the blocks are not invoked until after Tester.test returns.

Also, if I monitor web traffic, it appears (and this is hard to confirm) that the web request goes out as expected, but it's just that the block invocation from AFMotion is somehow starved, and not invoked until after everything else has finished.

I've included the test harness. You'll need the AFMotion and Futuristic gems running in a RubyMotion app for the test harness to work.

Any feedback would be much appreciated.

Regards,
M@

module Futuriser

  # Used to carry around lock/wait semaphores and the result from an async operation
  class Helper
    attr_accessor :semaphore1, :semaphore2, :result, :timeout, :timedout
    def initialize
      super
      @semaphore1 ||= Dispatch::Semaphore.new(0) # for syncing work completion
      @semaphore2 ||= Dispatch::Semaphore.new(1) # for syncing access to finite resources
      @result     ==  nil
      @timeout    ||= nil
      @timedout   =   false
    end
    def initWithTimeout(to)
      initialize
      @timeout = to
      self
    end
  end

  # Run the specified block and wait it finishes, returning the result
  def Futuriser.make_sync(timeout = nil, &block)
    fh = Helper.alloc.initWithTimeout(timeout)
    BubbleWrap::Reactor.schedule do
      block.arity == 0 ? fh.result = block.call : fh.result = block.call(fh) if block
      fh.semaphore2.wait(fh.timeout) # Wait for access to @result
      fh.semaphore1.signal
    end
    fh.timedout = !fh.semaphore1.wait(fh.timeout) # Wait for async task to complete or timeout
    fh.semaphore2.signal
    fh.result
  end

  # Test everything
  class Tester

    # Run all tests one after the other
    def Tester.test
      test_make_sync
      test_futurise
      test_afmotion_using_semaphores
      test_afmotion_using_futures
      print "\n"
    end

    # Test that make_async will wait until specified block is complete
    def Tester.test_make_sync
      print "\nFuturiser::Tester.test_make_sync\n"

      print "Running sleep(5) block synchronously..."
      result05 = Futuriser.make_sync(10) {|| sleep( 5);  5}     # will not timeout
      print "Done:result05\n"

      print "Running sleep(10) block synchronously..."
      result10 = Futuriser.make_sync(5) {|| sleep(10); 10}      # will timeout
      print "Done:result10\n"

      print "Testing results...\n"
      print "result05 == #{result05}   : #{result05 ==  5}\n"   # 5 because sleep < timeout
      print "result10 == nil : #{result10 == nil}\n"            # nil because of timeout
      print "Done:results\n"

      print "Done:test_make_sync\n"
    end

    # Test thtt the Futuristic gem works as advertised
    def Tester.test_futurise
      print "\nFuturiser::Tester.test_futurise\n"

      print "Creating future05..."
      future05 = Dispatch::Future.new do                        # start and return 5 to future when done
        sleep(5)
        5
      end
      print "Done:future05\n"

      print "Creating future10..."                              # start and return 10 to future when done
      future10 = Dispatch::Future.new do
        sleep(10)
        10
      end
      print "Done:future10\n"

      print "Waiting on future05..."
      result05 = future05.value                                 # Blocks until future05 finishes
      print "Done:future05\n"
      print "Waiting on future10..."
      result10 = future10.value                                 # Blocks until future10 finishes
      print "Done:future10\n"

      print "Testing results...\n"
      print "result05 == #{result05}  : #{result05 ==  5}\n"
      print "result10 == #{result10} : #{result10 == 10}\n"
      print "Done:results\n"

      print "Done:test_futurise\n"
    end

    # Test what happens when attempting to wait on an AFMotion 'get' request using semaphores
    def Tester.test_afmotion_using_semaphores
      print "\nFuturiser::Tester.test_afmotion_using_semaphores\n"

      @fh = Helper.alloc.initWithTimeout(5)

      print "Launching async web request...\n"
      AFMotion::HTTP.get("http://google.com") do |result|
        print "Got response from request using semaphores!\n"
        @fh.semaphore2.wait(@fh.timeout)                        # Wait for access to result
        @fh.result = result                                     # Store result for later
        @fh.semaphore1.signal                                   # Let waiter know we're done
        print "Done:semaphores_response\n"
      end
      print "Done:start_async\n"

      print "Waiting for async task to finish...\n"
      @fh.timedout = [email protected](@fh.timeout)          # Wait for async to complete or timeout
      @fh.semaphore2.signal                                     # Let async know we're ready
      print "Done:wait_on_async[timedout:#{@fh.timedout}]\n"

      print "Verify result...\n"
      print "@fh.result   != nil   : #{[email protected]?}\n"     # Should not be nil
      print "@fh.timedout == false : #{[email protected]}\n"        # Should not timeout
      print "Done:results\n"

      print "Done:test_afmotion_using_semaphores\n"
    end

    # Test what happens when attempting to wait on an AFMotion 'get' request using Futuristic futures
    def Tester.test_afmotion_using_futures
      print "\nFuturiser::Tester.test_afmotion_using_futures\n"

      @fh = Helper.alloc.initWithTimeout(5)

      print "Creating future to wrap web request...\n"
      future = Dispatch::Future.new do
        print "Launching async web request...\n"
        AFMotion::HTTP.get("http://google.com") do |result|
          print "Got response from request using futures!\n"
          @fh.semaphore2.wait(@fh.timeout)                      # Wait for access to result
          @fh.result = result                                   # Store result for later
          @fh.semaphore1.signal                                 # Let waiter know we're done
          print "Done:futures_response\n"
        end
        print "Done:web\n"
        print "Waiting for async task to finish...\n"
        @fh.timedout = [email protected](@fh.timeout)        # Wait for async to complete or timeout
        @fh.semaphore2.signal                                   # Let async know we're ready
        print "Done:wait_on_async[timedout:#{@fh.timedout}]\n"
      end
      print "Done:future.\n"

      print "Grab value from future...\n"
      result = future.value                                     # Should wait for future to complete
      print "Done:future.value\n"

      print "Verify result...\n"
      print "result       != nil   : #{!result.nil?}\n"         # Should not be nil
      print "@fh.timedout == false : #{[email protected]}\n"        # Should not timeout
      print "Done:result\n"

      print "Done:test_afmotion_using_futures\n"
    end

  end
end

I've also posted this over on the RubyMotion Google Groups here:

https://groups.google.com/d/msg/rubymotion/Rn7gm3M0mFQ/x0NaAiEQPFQJ

because the semaphore pattern I am using comes from that thread.

What am I missing about the way AFMotion invokes its block on completion of a web request

I've been doing some work trying to integrate @seanlilmateus Futuristic gem with AFMotion so that I can use futures to work with web requests instead of having to run multiple web requests inside nested blocks. However, I'm coming unstuck because of the way that AFMotion calls back its block when its web request is finished. For a reason that escapes me, the block is not invoked until after anything to do with either semaphores or Dispatch::Future from the Futuristic gem has finished.

So either I'm doing something crazy (entirely possible!) or there's something odd about the way AFMotion calls back it's block that is incompatible with either semaphores or futures (at least as I am using them here).

I've created a standalone test class that runs through four tests:

  1. test_make_sync: this uses the pattern described above in this thread to wait on a block. This works as expected.
  2. test_futurise: this uses the pattern described in @seanlilmateus Futuristic gem, and also works as I would expect it to.
  3. test_afmotion_using_semaphores: this test attempts to use the semaphore pattern from #1 to wait on execution of a call to AFMotion:HTTP.get. It doesn't work.
  4. test_afmotion_using_futures: this test attempts to use the future pattern from #2 to wait on execution of a call to AFMotion:HTTP.get. It doesn't work either.

The test can be invoked from the REPL via: Futuriser::Tester.test

If I run the test, I see that while #1 and #2 work according to plan, both #3 and #4 timeout before a result is returned. And in both #3 and #4, the block passed into the AFMotion::HTTP.get call is not invoked until well after everything else finishes. If I invoke Futuriser::Tester.test from the RubyMotion REPL, then the blocks are not invoked until after Tester.test returns.

Also, if I monitor web traffic, it appears (and this is hard to confirm) that the web request goes out as expected, but it's just that the block invocation from AFMotion is somehow starved, and not invoked until after everything else has finished.

I've included the test harness. You'll need the AFMotion and Futuristic gems running in a RubyMotion app for the test harness to work.

Any feedback would be much appreciated.

Regards,
M@

module Futuriser

  # Used to carry around lock/wait semaphores and the result from an async operation
  class Helper
    attr_accessor :semaphore1, :semaphore2, :result, :timeout, :timedout
    def initialize
      super
      @semaphore1 ||= Dispatch::Semaphore.new(0) # for syncing work completion
      @semaphore2 ||= Dispatch::Semaphore.new(1) # for syncing access to finite resources
      @result     ==  nil
      @timeout    ||= nil
      @timedout   =   false
    end
    def initWithTimeout(to)
      initialize
      @timeout = to
      self
    end
  end

  # Run the specified block and wait it finishes, returning the result
  def Futuriser.make_sync(timeout = nil, &block)
    fh = Helper.alloc.initWithTimeout(timeout)
    BubbleWrap::Reactor.schedule do
      block.arity == 0 ? fh.result = block.call : fh.result = block.call(fh) if block
      fh.semaphore2.wait(fh.timeout) # Wait for access to @result
      fh.semaphore1.signal
    end
    fh.timedout = !fh.semaphore1.wait(fh.timeout) # Wait for async task to complete or timeout
    fh.semaphore2.signal
    fh.result
  end

  # Test everything
  class Tester

    # Run all tests one after the other
    def Tester.test
      test_make_sync
      test_futurise
      test_afmotion_using_semaphores
      test_afmotion_using_futures
      print "\n"
    end

    # Test that make_async will wait until specified block is complete
    def Tester.test_make_sync
      print "\nFuturiser::Tester.test_make_sync\n"

      print "Running sleep(5) block synchronously..."
      result05 = Futuriser.make_sync(10) {|| sleep( 5);  5}     # will not timeout
      print "Done:result05\n"

      print "Running sleep(10) block synchronously..."
      result10 = Futuriser.make_sync(5) {|| sleep(10); 10}      # will timeout
      print "Done:result10\n"

      print "Testing results...\n"
      print "result05 == #{result05}   : #{result05 ==  5}\n"   # 5 because sleep < timeout
      print "result10 == nil : #{result10 == nil}\n"            # nil because of timeout
      print "Done:results\n"

      print "Done:test_make_sync\n"
    end

    # Test thtt the Futuristic gem works as advertised
    def Tester.test_futurise
      print "\nFuturiser::Tester.test_futurise\n"

      print "Creating future05..."
      future05 = Dispatch::Future.new do                        # start and return 5 to future when done
        sleep(5)
        5
      end
      print "Done:future05\n"

      print "Creating future10..."                              # start and return 10 to future when done
      future10 = Dispatch::Future.new do
        sleep(10)
        10
      end
      print "Done:future10\n"

      print "Waiting on future05..."
      result05 = future05.value                                 # Blocks until future05 finishes
      print "Done:future05\n"
      print "Waiting on future10..."
      result10 = future10.value                                 # Blocks until future10 finishes
      print "Done:future10\n"

      print "Testing results...\n"
      print "result05 == #{result05}  : #{result05 ==  5}\n"
      print "result10 == #{result10} : #{result10 == 10}\n"
      print "Done:results\n"

      print "Done:test_futurise\n"
    end

    # Test what happens when attempting to wait on an AFMotion 'get' request using semaphores
    def Tester.test_afmotion_using_semaphores
      print "\nFuturiser::Tester.test_afmotion_using_semaphores\n"

      @fh = Helper.alloc.initWithTimeout(5)

      print "Launching async web request...\n"
      AFMotion::HTTP.get("http://google.com") do |result|
        print "Got response from request using semaphores!\n"
        @fh.semaphore2.wait(@fh.timeout)                        # Wait for access to result
        @fh.result = result                                     # Store result for later
        @fh.semaphore1.signal                                   # Let waiter know we're done
        print "Done:semaphores_response\n"
      end
      print "Done:start_async\n"

      print "Waiting for async task to finish...\n"
      @fh.timedout = [email protected](@fh.timeout)          # Wait for async to complete or timeout
      @fh.semaphore2.signal                                     # Let async know we're ready
      print "Done:wait_on_async[timedout:#{@fh.timedout}]\n"

      print "Verify result...\n"
      print "@fh.result   != nil   : #{[email protected]?}\n"     # Should not be nil
      print "@fh.timedout == false : #{[email protected]}\n"        # Should not timeout
      print "Done:results\n"

      print "Done:test_afmotion_using_semaphores\n"
    end

    # Test what happens when attempting to wait on an AFMotion 'get' request using Futuristic futures
    def Tester.test_afmotion_using_futures
      print "\nFuturiser::Tester.test_afmotion_using_futures\n"

      @fh = Helper.alloc.initWithTimeout(5)

      print "Creating future to wrap web request...\n"
      future = Dispatch::Future.new do
        print "Launching async web request...\n"
        AFMotion::HTTP.get("http://google.com") do |result|
          print "Got response from request using futures!\n"
          @fh.semaphore2.wait(@fh.timeout)                      # Wait for access to result
          @fh.result = result                                   # Store result for later
          @fh.semaphore1.signal                                 # Let waiter know we're done
          print "Done:futures_response\n"
        end
        print "Done:web\n"
        print "Waiting for async task to finish...\n"
        @fh.timedout = [email protected](@fh.timeout)        # Wait for async to complete or timeout
        @fh.semaphore2.signal                                   # Let async know we're ready
        print "Done:wait_on_async[timedout:#{@fh.timedout}]\n"
      end
      print "Done:future.\n"

      print "Grab value from future...\n"
      result = future.value                                     # Should wait for future to complete
      print "Done:future.value\n"

      print "Verify result...\n"
      print "result       != nil   : #{!result.nil?}\n"         # Should not be nil
      print "@fh.timedout == false : #{[email protected]}\n"        # Should not timeout
      print "Done:result\n"

      print "Done:test_afmotion_using_futures\n"
    end

  end
end

I've also posted this over on the RubyMotion Google Groups here:

https://groups.google.com/d/msg/rubymotion/Rn7gm3M0mFQ/x0NaAiEQPFQJ

because the semaphore pattern I am using comes from that thread.

Multipart PUT is no longer available in AFMotion 2.0

With 0.9 I used to be able to do client.multipart!.put() to do a PUT. Think updating a profile page with a picture against a Rails backend.

Looking at the source multipart is now explicitly a POST operation and even create_multipart_operation does an explicit self.POST

Is there a reason for it, or is it just an oversight? Want a pull request or is it a quick fix for you?

Build Error

Hey Clay,

Probably something I'm doing(or did), but I'm getting this now.

Thanks

** BUILD FAILED **

The following build commands failed:
CompileC build/Pods.build/Release-iphonesimulator/Pods.build/Objects-normal/i386/AFHTTPClient.o AFNetworking/AFNetworking/AFHTTPClient.m normal i386 objective-c com.apple.compilers.llvm.clang.1_0.compiler
(1 failure)
rake aborted!
Command failed with status (65): [/usr/bin/xcodebuild -project "Pods.xcodepr...]

Tasks: TOP => default => simulator => build:simulator
(See full trace by running task with --trace)
[:AppDotNet]$ rake
Build ./build/iPhoneSimulator-5.0-Development
Build vendor/Pods
ERROR! Building vendor project vendor/Pods' failed to create at least one.a' library.

Frozen/immutable hash

Is there a way to return a mutable hash from result.object. Currently I get this can't modify frozen/immutable hash (RuntimeError) when I try to do this - result.object.delete(:first_name)

I am using v2.2.0

Multipart POST?

Hello,

I am trying to upload an image to my remote Rails API (with paperclip).
How can I do a multipart POST using Afmotion?

Thanks!

uninitialized constant AFMotion::JSON::AFJSONParameterEncoding

I can't get afmotion to work, it always gives me this error:

2014-05-27 16:26:42.515 appname[77784:70b] uninitialized constant AFMotion::JSON::AFJSONParameterEncoding (NameError)
=> #<NameError: uninitialized constant AFMotion::JSON::AFJSONParameterEncoding>

The code I'm using (with a valid url):

    AFMotion::JSON.get("http://myurl") do |result|
      p result.object
    end

Gemfile

source 'https://rubygems.org'

gem 'rake'
# Add your dependencies here:
gem 'sugarcube', :require => 'sugarcube-all'
gem 'bubble-wrap'
gem 'geomotion'
gem 'cocoapods'
gem 'motion-cocoapods'
gem 'json'
gem 'awesome_print_motion'
gem 'motion-firebase'
gem 'afmotion'

Rakefile

# -*- coding: utf-8 -*-
$:.unshift("/Library/RubyMotion/lib")
require 'motion/project/template/ios'

begin
  require 'bundler'
  Bundler.require
rescue LoadError
end

Motion::Project::App.setup do |app|
  # Use `rake config' to see complete project settings.
  app.detect_dependencies = false
  app.frameworks += ["OpenGLES","SystemConfiguration","QuartzCore","CoreLocation","CoreMedia","MapKit","CoreText","CoreImage","MessageUI","Accounts","Social","AdSupport","StoreKit","CoreGraphics","GPUImage"]

  app.pods do
    pod 'COSTouchVisualizer'
    pod 'ADTransitionController'
    pod 'SVProgressHUD'
    pod 'CSNotificationView'
  end

  app.vendor_project('vendor/FacebookSDK.framework', :static,
    :products => ['FacebookSDK'],
    :headers_dir => 'Headers')
  app.vendor_project('vendor/Parse.framework', :static,
    :products => ['Parse'],
    :headers_dir => 'Headers')
end

versions

rubymotion 2.28
ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-darwin12.3.0]

I did a rake clean:all + rake pod:install + rake before also. Also tried adding pod 'AFNetworking' to the rakefile, but this didn't help.

Full stack trace

2014-05-27 16:33:01.229 Untitled[78799:70b] *** Terminating app due to uncaught exception 'NameError', reason: 'app_delegate.rb:18:in `async_load': uninitialized constant AFMotion::JSON::AFJSONParameterEncoding (NameError)
    from splash.rb:27:in `viewDidAppear:'
'
*** First throw call stack:
(
    0   CoreFoundation                      0x03c121e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x0137b8e5 objc_exception_throw + 44
    2   Untitled                            0x00b22d1a _ZL10__vm_raisev + 346
    3   Untitled                            0x00b22df8 rb_vm_raise + 216
    4   Untitled                            0x00a26361 rb_exc_raise + 17
    5   Untitled                            0x00a1fba7 rb_name_error + 135
    6   Untitled                            0x00adb775 rb_mod_const_missing + 165
    7   Untitled                            0x00b17b9d _ZL20dispatch_rimp_callerPFP11objc_objectS0_P13objc_selectorzEmS1_iPKm + 46445
    8   Untitled                            0x00afe5ba rb_vm_dispatch + 6554
    9   Untitled                            0x00adc5e6 rb_const_get_0 + 1046
    10  Untitled                            0x00adc6e0 rb_const_get + 32
    11  Untitled                            0x00b1ace2 rb_vm_const_lookup_level + 338
    12  Untitled                            0x00388b83 vm_get_const + 227
    13  Untitled                            0x00392634 rb_scope__parameter_encoding__4 + 68
    14  Untitled                            0x00b17b9d _ZL20dispatch_rimp_callerPFP11objc_objectS0_P13objc_selectorzEmS1_iPKm + 46445
    15  Untitled                            0x00afe5ba rb_vm_dispatch + 6554
    16  Untitled                            0x0038907c vm_dispatch + 1100
    17  Untitled                            0x00391b07 rb_scope__included:__block__1 + 1815
    18  Untitled                            0x00b0c48b _ZL20dispatch_bimp_callerPFP11objc_objectS0_P13objc_selectorzEmS1_mP11rb_vm_blockiPKm + 46507
    19  Untitled                            0x00aff8b1 _ZL13vm_block_evalP7RoxorVMP11rb_vm_blockP13objc_selectormiPKm + 1137
    20  Untitled                            0x00affbc8 rb_vm_block_eval2 + 104
    21  Untitled                            0x00b201d2 rb_vm_block_method_imp + 706
    22  Untitled                            0x00afdf26 rb_vm_dispatch + 4870
    23  Untitled                            0x009adc1c vm_dispatch + 1100
    24  Untitled                            0x009b64c6 rb_scope__async_load__ + 326
    25  Untitled                            0x00b17b9d _ZL20dispatch_rimp_callerPFP11objc_objectS0_P13objc_selectorzEmS1_iPKm + 46445
    26  Untitled                            0x00afe5ba rb_vm_dispatch + 6554
    27  Untitled                            0x009e54ec vm_dispatch + 1100
    28  Untitled                            0x009eddb8 rb_scope__viewDidAppear:__ + 248
    29  Untitled                            0x009eddec __unnamed_15 + 44
    30  UIKit                               0x02343099 -[UIViewController _setViewAppearState:isAnimating:] + 526
    31  UIKit                               0x02343617 -[UIViewController __viewDidAppear:] + 146
    32  UIKit                               0x023438a1 -[UIViewController _endAppearanceTransition:] + 306
    33  UIKit                               0x02354136 -[UIViewController(UIContainerViewControllerProtectedMethods) endAppearanceTransition] + 41
    34  Untitled                            0x00087c8e -[ADTransitionController viewDidAppear:] + 103
    35  UIKit                               0x02343099 -[UIViewController _setViewAppearState:isAnimating:] + 526
    36  UIKit                               0x02343617 -[UIViewController __viewDidAppear:] + 146
    37  UIKit                               0x02345014 __64-[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:]_block_invoke + 44
    38  UIKit                               0x023439aa -[UIViewController _executeAfterAppearanceBlock] + 63
    39  UIKit                               0x0223e0d0 ___afterCACommitHandler_block_invoke_2 + 33
    40  UIKit                               0x0223e055 _applyBlockToCFArrayCopiedToStack + 403
    41  UIKit                               0x0223de9a _afterCACommitHandler + 568
    42  CoreFoundation                      0x03bda36e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
    43  CoreFoundation                      0x03bda2bf __CFRunLoopDoObservers + 399
    44  CoreFoundation                      0x03bb8254 __CFRunLoopRun + 1076
    45  CoreFoundation                      0x03bb79d3 CFRunLoopRunSpecific + 467
    46  CoreFoundation                      0x03bb77eb CFRunLoopRunInMode + 123
    47  GraphicsServices                    0x06bce5ee GSEventRunModal + 192
    48  GraphicsServices                    0x06bce42b GSEventRun + 104
    49  UIKit                               0x02220f9b UIApplicationMain + 1225
    50  Untitled                            0x001b132c main + 156
    51  libdyld.dylib                       0x056f2701 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NameError

There no way to set cachePolicy for request

Hi.

I've just found that there no way to set cachePolicy for request using afmotion api. So only way is to remove cached request from NSURLCache.sharedURLCache :(

It will be very helpful to have additional argument for request methods, to be able to set NSURLRequest options.

Thank you!

License missing from gemspec

RubyGems.org doesn't report a license for your gem. This is because it is not specified in the gemspec of your last release.

via e.g.

spec.license = 'MIT'
# or
spec.licenses = ['MIT', 'GPL-2']

Including a license in your gemspec is an easy way for rubygems.org and other tools to check how your gem is licensed. As you can image, scanning your repository for a LICENSE file or parsing the README, and then attempting to identify the license or licenses is much more difficult and more error prone. So, even for projects that already specify a license, including a license in your gemspec is a good practice. See, for example, how rubygems.org uses the gemspec to display the rails gem license.

There is even a License Finder gem to help companies/individuals ensure all gems they use meet their licensing needs. This tool depends on license information being available in the gemspec. This is an important enough issue that even Bundler now generates gems with a default 'MIT' license.

I hope you'll consider specifying a license in your gemspec. If not, please just close the issue with a nice message. In either case, I'll follow up. Thanks for your time!

Appendix:

If you need help choosing a license (sorry, I haven't checked your readme or looked for a license file), GitHub has created a license picker tool. Code without a license specified defaults to 'All rights reserved'-- denying others all rights to use of the code.
Here's a list of the license names I've found and their frequencies

p.s. In case you're wondering how I found you and why I made this issue, it's because I'm collecting stats on gems (I was originally looking for download data) and decided to collect license metadata,too, and make issues for gemspecs not specifying a license as a public service :). See the previous link or my blog post about this project for more information.

instance_eval in builders

Hi.

I don't think that using instance_eval in build blocks is even close to being a good idea, since it messes with self and instantly converts this simple code to nuclear F-Bomb:

AFMotion::SessionClient.build(Url) do
  header "X-My-Stuff", @x_my_header #Good luck with debugger, mate

  response_serializer :json
end

Yes, instance_eval is awesome tool for creating "out-of-context" DSL's, like routes.rb. But in this case, this forces to do it like:

magic_context_gateway = {this: @so, that: @wow}
AFMotion::SessionClient.build(Url) do
  header "X-My-Stuff", magic_context_gateway[:this] # YAY!

  response_serializer :json
end

And that makes this kitten very sad :(
3445973356_2f8510869b

Make kitty happy, don't instance_eval builder blocks, yield 'em!

Thank you!

Status code?

Hello,

Is there a quick way of getting the status code when connection fails (when result.failure)?

Failing specs for session_client_spec.rb

I've been trying to get the specs passing but session_client_spec.rb fails around line 120 with error:

2013-11-09 08:55:03.850 AFMotion[59303:80b] *** Terminating app due to uncaught exception 'NoMethodError', reason: 'operation.rb:27:in `block in failure_block:': undefined method `responseObject' for #<__NSCFLocalDataTask:0x8e27890> (NoMethodError)

I believe this is because `operation.rb tries to parse a response which returned a wrong content/type. Looking at AFNetworking the failure_block should first check if the returned failure response has the same content/type as requested. As found in issue #1280 https://github.com/AFNetworking/AFNetworking/issues/1280

Fromt the REPL I checked the @results returned error code which indeed is -1016.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html

The strange thing is that the requestSerializer is a AFHTTPRequestSerializer and the result returned does have content/type http

#<AFMotion::HTTPResult:0xeb0d8c0 @task=#<__NSCFLocalDataTask:0x11b5bc40> @object=nil @error=#<NSError:0x11b5a660, description="Request failed: unacceptable content-type: text/html", code=-1016, domain="AFNetworkingErrorDomain", userInfo={"NSErrorFailingURLKey"=>#<NSURL:0xeb0f500>, "AFNetworkingOperationFailingURLResponseErrorKey"=>#<NSHTTPURLResponse:0xeb0e9a0>, "NSLocalizedDescription"=>"Request failed: unacceptable content-type: text/html"}>>

Should the spec be changed to make a request and return the correct content/type or should the failure_block be changed to first check if the response could be parsed?

Setting cookies/sessions

I'm trying to authenticate against a backend but am not sure on how to implement setting the http_cookie. (I think it should be handled by afnetworking itself?). The authentication itself works and while the app stays in the foreground I am authenticated. When I close the app the session seems to be cleared.

AFMotion::Client.build_shared(Web.base_url) do
  header "Accept", "application/json"

  response_serializer :json
end

And in my request:

  AFMotion::Client.shared.get(url, data) do |response|
    blk.call(response)
  end

Or
AFMotion::Client.shared.post(url, data) do |response|
blk.call(response)
end

I can't figure out where to set the cookie header for the requests. Should I need to and if so where/how to configure this?

SessionClient not working (NoMethodError(s))

I'm having some struggle by creating a SessionClient...
This is my code:

class API < AFMotion::SessionClient

  attr_accessor :api

  class << self

    def new
      @api = build( Api_url )
        session_configuration :default

        header "Accept", "application/json"
        header "Content-Type", "application/json"
      end

    end

end

But it returns a 'NoMethodError':

2013-11-19 13:06:32.631 Blossom[76633:80b] session_client.rb:107:in `session_configuration:': undefined method `sessionConfiguration=' for nil:NilClass (NoMethodError)
    from api.rb:9:in `block in new'
    from session_client.rb:26:in `build:'
    from api.rb:8:in `new'
    from app_delegate.rb:14:in `on_load:'
    from delegate_module.rb:16:in `application:didFinishLaunchingWithOptions:'
2013-11-19 13:06:32.648 Blossom[76633:80b] *** Terminating app due to uncaught exception 'NoMethodError', reason: 'session_client.rb:107:in `session_configuration:': undefined method `sessionConfiguration=' for nil:NilClass (NoMethodError)
    from api.rb:9:in `block in new'
    from session_client.rb:26:in `build:'
    from api.rb:8:in `new'
    from app_delegate.rb:14:in `on_load:'
    from delegate_module.rb:16:in `application:didFinishLaunchingWithOptions:'

In my app_delegate.rb I'm making a API.new call.

I did some changes by myself via forking this repo;

# afmotion/lib/afmotion/session_client.rb

...

     def to_session_manager
      session_manager = AFHTTPSessionManager.alloc.initWithBaseURL(@base_url.to_url,
          # sessionConfiguration: config.sessionConfiguration)
          sessionConfiguration: SESSION_CONFIGURATION_SHORTHAND['default'])
      session_manager.responseSerializer = config.responseSerializer if config.responseSerializer
      if !config.requestSerializer.is_a?(Config::MockRequestSerializer)
        session_manager.requestSerializer = config.requestSerializer

...

This solved my first NoMethodError, but rises a new one;

2013-11-19 12:52:58.459 Blossom[74117:80b] session_client.rb:79:in `to_session_manager': undefined method `responseSerializer' for nil:NilClass (NoMethodError)
    from session_client.rb:31:in `build:'
    from api.rb:8:in `new'
    from app_delegate.rb:14:in `on_load:'
    from delegate_module.rb:16:in `application:didFinishLaunchingWithOptions:'
2013-11-19 12:52:58.473 Blossom[74117:80b] *** Terminating app due to uncaught exception 'NoMethodError', reason: 'session_client.rb:79:in `to_session_manager': undefined method `responseSerializer' for nil:NilClass (NoMethodError)
    from session_client.rb:31:in `build:'
    from api.rb:8:in `new'
    from app_delegate.rb:14:in `on_load:'
    from delegate_module.rb:16:in `application:didFinishLaunchingWithOptions:'

Maybe I'm missing something when building the SessionClient?!

Thanks in advance,

Sander

Getting result.object on failure?

Hi,

I'm currently migrating from BW to AFMotion, but I'm stuck in something, maybe it's easy, but not for me after 3 hours looking around the AFMotion source.

I'm calling my API endpoint and then returning error when parameters are wrong (rails validations) putting that error messages in errors hash in the json response.

When i'm receiving the "result.failure?" the result.object is nil/empty and then I cannot access to this data, is there any way to reach this data on failure ?

Many thanks in advance.

not an issue per se, i suppose..

Clay, any idea how we might be able to compile AFNetworking with the _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ feature flag? I'm scratching my head over this one, thought you might have an insight.

Here's the discussion about the flag (long and boring!) AFNetworking/AFNetworking#204. It boils down to defining and recompiling.

How to use Etag?

Hello,

I am using your wonderful gem with a shared connection and it works fine. Now I need to add a custom header (If-None-Match) along with latest Etag to check if anything has changed.

I am using AFMotion::Client.build_shared in the app_delegate so I cannot pass an Etag there. Is there a way to do it in this call AFMotion::Client.shared.get?

I guess I am asking if I can add custom headers to shared calls or perhaps if it is possible to pass Etag in some way?

Thanks!

AFMotion cannot retrieve unusually formatted URLs

This query returns the wrong page, probably because it's stripping the parameters off at some level:

AFMotion::HTTP.get("http://viv.ebay.com/ws/eBayISAPI.dll?EbayTime") do |result|
  p result.body
end

Expected: The official time page of eBay to be returned.
Actual: An error page is returned.

Using If-None-Match?

Hello,

How can I use caching, with for example the Etag header:

header "If-None-Match", "20ac70eb53c8b5d234dda0477a87cc70"

I tried adding it to: AFMotion::Client.build_shared just for testing and hard cording the Etag but that made no difference.

Cannot retrieve image bits using HTTP.get

The following code fails to retrieve the bits of the image, for processing or storage.

AFMotion::HTTP.get("https://www.google.com/images/srpr/logo11w.png") do |result|
  p result.success?
  if result.success?
    p result.body # Ugly, but for demonstration purposes.
  else
    p result.error.localizedDescription
  end
end

Expected: A dump of the bits from the google logo.
Actual: "Request failed: unacceptable content-type: image/png"

Set expected content type

I'm trying to verify iTunes receipt with AFMotion (for in-app purchases), but can't set the content type. Keep getting this error:

Expected content type {(\\n    \\\"text/json\\\",\\n    \\\"text/javascript\\\",\\n    \\\"application/json\\\",\\n    \\\"text/html\\\"\\n)}, got text/plain\

Using this code:

encoder = CocoaSecurityEncoder.new
json_data = {"receipt-data" => encoder.base64(receipt), "password" => @shared_secret}
AFJSONRequestOperation.addAcceptableContentTypes(NSSet.setWithObject("text/html"))
AFMotion::JSON.get("https://sandbox.itunes.apple.com/verifyReceipt", q:json_data) do |result|
  ap "BODY: #{result.body}" if result.body
  ap "OBJECT: #{result.object}" if result.object
  ap "ERROR: #{result.error}" if result.error
end

If I use AFNetworking, I can get it to work with:

encoder = CocoaSecurityEncoder.new
json_data = {"receipt-data" => encoder.base64(receipt), "password" => @shared_secret}
baseURL = NSURL.URLWithString("https://sandbox.itunes.apple.com")

client = AFHTTPClient.alloc.initWithBaseURL(baseURL)
client.setDefaultHeader("Accept", value:"application/json")
client.registerHTTPOperationClass(AFJSONRequestOperation.class)
client.setParameterEncoding(AFJSONParameterEncoding)
AFJSONRequestOperation.addAcceptableContentTypes(NSSet.setWithObject("text/plain"))

request = client.requestWithMethod("POST", path:"verifyReceipt", parameters:json_data)
requestOperation = client.HTTPRequestOperationWithRequest(request, success: lambda { |operation, responseObject| 
  ap "operation: #{operation}"
  ap "responseObject: #{responseObject}"
}, failure: lambda {|operation, error|
  ap "operation: #{operation}"
  ap "error: #{error}"
})

But it looks so clumsy, compared to the above code.

Is there any way I can set the expected content type for the original code in AFMotion?

Getting BACKTRACE: Bacon::Error: timeout exceeded for specs

I'm getting this message when I'm trying to run specs for requests done using AFMotion:

 it "should return get request" do
    url = Apify::Router.routes[:languages].url

    resp = ""
    AFMotion::HTTP.get(url) do |result|
      resp = result.body.to_str
    end

    wait_max 15.0 do
      resp.should.eql ""
    end
  end
[FAILED] - should return get request
BACKTRACE: Bacon::Error: timeout exceeded: REST - should return get request
    spec.rb:352:in `block in postponed_block_timeout_exceeded': REST - should return get request
    spec.rb:403:in `execute_block'
    spec.rb:352:in `postponed_block_timeout_exceeded'

Progress callback with multipart_upload broken

Love afmotion - it cut away some good chunks of code from my API-client. Thanks!

client.multipart_post(path, params) do |result, form_data, progress|

with AFMotion::SessionClient appear to be broken. The callback appear to be only called once to get form data so no progress is ever reported.

I looked into the source code in hope of contributing a fix but it's a bit too convoluted for me to debug.

It looks like there's a typo with PUT requests:
success: AFMotion::Operation.success_block_for_http_method(:pust, inner_callback), but that's not the issue I'm experiencing.

Any ideas what could be wrong?

Can't post json. Wrong request type

Hello, I'm not sure if I'm doing something wrong here, but I can't seem to post json.

client = AFMotion::SessionClient.build("http://logs-01.loggly.com/") do
  session_configuration :default
  header "Accept", "application/json"
  header "Content-Type", "application/json"
  response_serializer :json
  request_serializer :json
end
puts client.headers['Content-Type']

client.post("inputs/TOKEN/tag/msg", :name => "ruby") do |result|

  puts result.success?
  puts result.error.to_s

end

For some reason, I keep getting back an error saying that the client request html, and not json

Advice how to cancel a task

I see a ton of conflicting information regarding canceling requests with AFNetworking, even from matt himself. I see some people say that when you cancel, the success callback will always be called and you must manually check .isCancelled on the operation, and i'm assuming for NSURLSessionTask maybe result.task.state

Anyways, whenever i cancel a task, the success callback is always being called and inspecting result.task.state i get NSURLSessionTaskStateCompleted = 3,

Here is the success block that i'm trying to prevent when canceling

https://gist.github.com/rromanchuk/92b78b1f3a6dd4e12b39

AFMotion::SessionClient.build forces you to provide a block

If no block is provided AFMotion::SessionClient.build throws an exception, is that expected behavior?

Right now I have to do something like this:

# Using an empty block here
http_client_helper(:host_url).post(AppRequest::URL_AUTH_SIGNOUT) { |_result| }

def http_client_helper(type = :api_url)
  url = type == :api_url ? URL_BASE : URL_HOST

  all_headers = headers

  AFMotion::SessionClient.build(url) do
    session_configuration :default
    all_headers.each { |key, value| header(key, value) }
    response_serializer :json
  end
end

Cocoa error 3840

Hi,

Currently I'm using AFMotion, but the put request fail and I'm not quite sure why it fails. AFMotion/AFNetworking gives me the cocoa error 3840, but I don't understand why, because I'm converting everything to a JSON object.

The client is created using a shared client.

Any idea on this?

  # Update an existing model
  def update( data, remote = false )
    data_attributes = BW::JSON.generate( data.attributes )
    item = if remote
      @client.put("#{@collection}/#{data.id}", data_attributes) do |res|
        p res
        if res.success?
          res.object
        end
      end
    else
      @model.where(:id).eq(data.id).first.update_attributes(data)
    end
  end
#<AFMotion::HTTPResult:0xa4df2f0 @operation=#<AFHTTPRequestOperation:0xe1d4570> 
@object=nil 
@error=#<NSError:0xa518f40, description="The operation couldn’t be completed. (Cocoa error 3840.)", code=3840, domain="NSCocoaErrorDomain", userInfo={"NSDebugDescription"=>"JSON text did not start with array or object and option to allow fragments not set."}>>

These are the Ruby Gem versions I'm using:

Using rake (10.1.0) 
Using ProMotion (1.0.4) 
Using i18n (0.6.5) 
Using multi_json (1.8.2) 
Using activesupport (3.2.15) 
Using claide (0.3.2) 
Using json_pure (1.8.1) 
Using nap (0.5.1) 
Using cocoapods-core (0.27.1) 
Using cocoapods-downloader (0.2.0) 
Using colored (1.2) 
Using escape (0.0.4) 
Using open4 (1.3.0) 
Using xcodeproj (0.14.1) 
Using cocoapods (0.27.1) 
Using motion-cocoapods (1.4.0) 
Using motion-require (0.0.7) 
Using afmotion (2.0.0) 
Using bubble-wrap (1.3.0) 
Using motion-support (0.2.5) 
Using motion-testflight (1.5) 
Using motion_model (0.4.6) 
Using sugarcube (1.3.5) 
Using teacup (2.1.13) 
Using sweettea (0.6.0) 
Using bundler (1.3.5) 

We're currently not using the latest cocoa pods, because the latest version of cocoa pods conflicts with some other gems.

Cheers.

Crash using example code from README

Using example code from the wiki to create a basic client, i'm getting a crash at build

@client = AFMotion::Client.build("https://alpha-api.app.net/") do
      header "Accept", "application/json"

      response_serializer :json
    end

2013-11-22 11:26:50.098 Frontback ⍺[20588:80b] app_delegate.rb:209:in block in setupClient': undefined methodresponse_serializer' for #<AFMotion::ClientDSL:0xde4fd90 ...> (NoMethodError)
from http_client.rb:65:in build:' from app_delegate.rb:206:insetupClient'
from app_delegate.rb:1:in `application:didFinishLaunchingWithOptions:'

o_O

Time out uploading files

Hi guys,

I'm trying to get into work with file uploads hitting an api made with sinatra, I`ve been facing the following, strange, behavior ,

  • in mi local environment it work just fine, the files are no more than 500k,
  • but in production the AFM progress always gets the 50% and then I have a time out error.
  • The thing is that with CURL uploading the same file takes no more than 4 secs. And it works concurrently too.
  • Also I´ve increased the timeouts in ruby server (unicorn) and nginx, but it seems that the problem is in my ios app.

Maybe Im doing something wrong here. Can you guys give me some pointers, what do you think about this code ?

      client = AFMotion::Client.build("#{Config.webservice_uri}/") 

     avatar_data = UIImageJPEGRepresentation(image, 0.8)

      client.multipart_post("uploads") do |result, form_data, progress|
          if form_data
            form_data.appendPartWithFileData(avatar_data, name: "data", fileName:"#{data_hash}.jpg", mimeType: "image/jpeg")
          elsif progress
            progress_percentage = (progress * 100.0).round(1)
            NSLog "#{progress_percentage}%"
          elsif result.success?
            NSLog("FILE UPLOADED #{result.body.to_s}")
          else
            NSLog(result.error.localizedDescription)
          end
        end

new error compiling

Objective-C stub for message registerHTTPOperationClass:' typec@:#' not precompiled. Make sure you properly link with the framework or library that defines this message.
((null))> rake aborted!

AFMotion exists specs early

I solved previous error using resume, but now my assertions don't get called.

  it "should return get request" do
    url = Apify::Router.routes[:languages].url    
    resp = ""

    AFMotion::JSON.get(url) do |result|
      resp = result.body.to_str
      resume
    end

    wait_max 15.0 do
      resp.should.equal stub_response(:languages)
      raise "something".inspect
    end
  end

It doesn't enter in the wait_max block, as I'm not getting any error.

Nil for result.operation.response

AFMotion::Client.shared.post("users/login", username: @username_field.text, password: @password_field.text) do |result|

      if result.success?

      elsif result.failure?
        puts result.error.localizedDescription

        puts result.operation.response.class => NilClass



    end

I am trying to get the status code but it respond with nilclass, please advise

uninitialized constant AFMotion::HTTP::AFFormURLParameterEncoding

I'm getting this error in my project. I think it is the same error as this one - #10.

If I run the sample project, then I can use afmotion with no problem, but it doesn't work in my project. I don't know if it's a gem conflict or what it is, but I really hope there's some sort of solution to this problem.

This is the error I get:

2013-06-21 16:32:50.736 Uninkd Previewer[39862:c07] http.rb:37:in `parameter_encoding': uninitialized constant AFMotion::HTTP::AFFormURLParameterEncoding (NameError)
  from layout.rb:175:in `layout:'
  from teacup_controller.rb:101:in `teacupDidLoad'
  from ui_view_controller.rb:6:in `viewDidLoad'
  from intro_controller.rb:45:in `viewDidLoad'
  from layout.rb:175:in `layout:'
  from teacup_controller.rb:101:in `teacupDidLoad'
  from ui_view_controller.rb:6:in `viewDidLoad'
  from root_controller.rb:17:in `viewDidLoad'
  from app_delegate.rb:18:in `application:didFinishLaunchingWithOptions:'
2013-06-21 16:32:50.738 Uninkd Previewer[39862:c07] *** Terminating app due to uncaught exception 'NameError', reason: 'http.rb:37:in `parameter_encoding': uninitialized constant AFMotion::HTTP::AFFormURLParameterEncoding (NameError)
  from layout.rb:175:in `layout:'
  from teacup_controller.rb:101:in `teacupDidLoad'
  from ui_view_controller.rb:6:in `viewDidLoad'
  from intro_controller.rb:45:in `viewDidLoad'
  from layout.rb:175:in `layout:'
  from teacup_controller.rb:101:in `teacupDidLoad'
  from ui_view_controller.rb:6:in `viewDidLoad'
  from root_controller.rb:17:in `viewDidLoad'
  from app_delegate.rb:18:in `application:didFinishLaunchingWithOptions:'

Gemfile:

# A sample Gemfile
source "https://rubygems.org"

gem "afmotion"
gem "teacup"
gem "sugarcube"
gem "sweettea"
gem 'bubble-wrap'
# gem "motion-awesome" # now handled by sugarcube-awesome
gem "geomotion"
gem "motion-schemes"
# gem "motion-cocoapods"
#gem "motion-xray"
# gem "motion-rubberstamp"#, :git => "[email protected]:IconoclastLabs/motion-rubberstamp.git"
group :development do
  gem "awesome_print_motion"
end

Rakefile:

# -*- coding: utf-8 -*-
$:.unshift("/Library/RubyMotion/lib")
require 'motion/project/template/ios'

# Require bundler
require 'bundler'
Bundler.require

# Require wrappers
# require 'rubygems'
# require 'motion-schemes'
# require 'motion-cocoapods'
require 'afmotion'
# require 'sugarcube'
# require 'sugarcube-568'
# require 'bubble-wrap'
# require 'teacup'
# require 'geomotion'

# Create new properties 
require './lib/app_properties'
previewer_props = AppProperties.new(name: 'Uninkd Previewer', path_name: '1_Previewer', development_license: 'iPhone Distribution: Uninkd, LLC.', distribution_license: 'iPhone Developer: Per Hakansson (JK2VU4L6Y2)', id: 'previewer')

Motion::Project::App.setup do |app|
  app.name =                            previewer_props.name
  app.version =                         previewer_props.version
  app.short_version =                   previewer_props.short_version

  app.identifier =                      previewer_props.identifier
  app.resources_dirs =                  previewer_props.resources_dirs

  app.frameworks =                      previewer_props.frameworks
  app.resources_dirs =                  previewer_props.resources_dirs
  app.files +=                          Dir.glob(File.join(app.project_dir, 'lib/**/*.rb'))

  app.deployment_target =               previewer_props.deployment_target
  app.sdk_version =                     previewer_props.sdk_version

  app.icons =                           previewer_props.icons
  app.fonts =                           previewer_props.fonts
  app.prerendered_icon =                previewer_props.prerendered_icon

  app.device_family =                   previewer_props.device_family
  app.interface_orientations =          previewer_props.interface_orientations

  app.info_plist['CFBundleIcons'] =     previewer_props.newsstand_icons
  app.info_plist['UINewsstandApp'] =    previewer_props.newsstand_app
  app.info_plist['UIBackgroundModes'] = previewer_props.background_modes
  app.info_plist['UIStatusBarHidden'] = previewer_props.statusbar_hidden
  app.info_plist['UIStatusBarStyle'] =  previewer_props.statusbar_style

  app.development do
    app.codesign_certificate =          'iPhone Developer: Per Hakansson (JK2VU4L6Y2)'
  end

  app.release do
    # app.codesign_certificate = 'iPhone Distribution: Your Name Here'
    # app.provisioning_profile = '/path/to/your/distribution_provisioning_profile.mobileprovision'
  end

  app.pods do
    pod 'QBFlatButton', :git => 'https://github.com/holgersindbaek/QBFlatButton.git', :branch => 'master'
    # pod 'QBFlatButton', :path => '~/Projects/*Defaults/Misc/Cocoapods/QBFlatButton', :branch => 'master'
    pod 'SKInnerShadowLayer', '~> 1.1'
    # pod 'SSToolkit', '~> 1.0.4'
    pod 'SSTextField', :path => '~/Projects/*Defaults/Misc/Cocoapods/SSTextField', :branch => 'master'
    pod 'DTCoreText', '~> 1.5.3'
    pod 'MSLabel', '~> 0.0.1'
    pod 'AFNetworking'
    pod 'Reachability'
    pod 'BPStatusBar', :git => 'https://github.com/holgersindbaek/BPStatusBar.git', :branch => 'master'
  end
end

Motion::Project::App.scheme(:Made) do |app|
end

intro_controller.rb:

class IntroController < UIViewController
  include BaseHelper
  include IntroHelper
  stylesheet :intro

  # Layout code via teacup
  layout :intro do
    @container = subview(UIView, :container) do
      @signup_label = subview(MSLabel, :signup_label)
      @signup_button = button(:signup_button, {title: 'PREVIEW'})
      @signup_input = input(:signup_input, {delegate: self})
    end

    AFMotion::HTTP.get("http://google.com") do |result|
      p result.body
    end

    # @signup_input.becomeFirstResponder
    @signup_button.when(UIControlEventTouchUpInside) do
      if internet_connected?
        BPStatusBar.showErrorWithStatus("No Connection")
        # return
      end

      BW::HTTP.get("http://#{@signup_input.text}.uninkd.com/existence.plist") do |response|
        if response.ok?
          plist = response.body.to_s.propertyListFromStringsFileFormat
          p plist[:Cover]
        else

        end
      end
    end

    @signup_input.on :editing_did_begin do
      keyboard_height = Device.ipad? ? 264 : 216
      @container.move_to([20, (Device.screen.height-keyboard_height)/2-(@container.frame.size.height/2)], duration: 0.25)
    end
  end  

  def layoutDidLoad
  end

  def viewDidLoad
    super
  end

end

result.operation is nil when calling AFMotion::JSON.get

After upgrading to the latest version of RubyMotion, the following code does not work anymore, because result.operation is 'nil'.

We are using RubyMotion v2.9 and AFMotion 0.9.0. The problem started occurring when we upgrade RubyMotion from v2.3 to v2.9.

  def initAndGet(url)
    @isFailed = false
    request = self.createRequest url
    AFMotion::JSON.get(request) do |result|
      handleResponse(request, result)
    end
  end

  def handle_response(request, result)
    response = result.operation.response
    if response
      if (response.statusCode() >= 200 and response.statusCode() <= 299)
        onSuccess(result, response)
      else
        onError(result, response.statusCode())
        @isFailed = true
      end
    else
      onConnectionError(request)
    end

    @delegate.request_done(self) if @delegate and @delegate.respond_to? :request_done
    onDone
  end

AFNetworking Error

I keep on getting this error when I run "bundle exec rake device"
Build ./build/iPhoneOS-7.1-Development
Build vendor/Pixate.framework
Link ./build/iPhoneOS-7.1-Development/kaibigan_app.app/kaibigan_app
final section layout:
__TEXT/__text addr=0x000088A0, size=0x01003398, fileOffset=0x000048A0, type=1
__TEXT/__picsymbolstub4 addr=0x0100BC38, size=0x000030E0, fileOffset=0x01007C38, type=27
__TEXT/__stub_helper addr=0x0100ED18, size=0x00002214, fileOffset=0x0100AD18, type=31
__TEXT/__objc_classname addr=0x01010F2C, size=0x00002353, fileOffset=0x0100CF2C, type=13
__TEXT/__cstring addr=0x01013280, size=0x0003BC84, fileOffset=0x0100F280, type=12
__TEXT/__objc_methname addr=0x0104EF04, size=0x00016F7F, fileOffset=0x0104AF04, type=13
__TEXT/__objc_methtype addr=0x01065E83, size=0x0000387E, fileOffset=0x01061E83, type=13
__TEXT/__gcc_except_tab addr=0x01069704, size=0x0000F160, fileOffset=0x01065704, type=0
__TEXT/__const addr=0x01078870, size=0x0004340C, fileOffset=0x01074870, type=0
__TEXT/__ustring addr=0x010BBC7C, size=0x00000020, fileOffset=0x010B7C7C, type=15
__TEXT/__dof_macruby addr=0x010BBC9C, size=0x00000355, fileOffset=0x010B7C9C, type=20
__DATA/__nl_symbol_ptr addr=0x010BC000, size=0x000009C4, fileOffset=0x010B8000, type=28
__DATA/__la_symbol_ptr addr=0x010BC9C4, size=0x00000C38, fileOffset=0x010B89C4, type=26
__DATA/__mod_init_func addr=0x010BD5FC, size=0x0000000C, fileOffset=0x010B95FC, type=32
__DATA/__const addr=0x010BD610, size=0x00009598, fileOffset=0x010B9610, type=0
__DATA/__objc_classlist addr=0x010C6BA8, size=0x000005DC, fileOffset=0x010C2BA8, type=0
__DATA/__objc_nlclslist addr=0x010C7184, size=0x00000080, fileOffset=0x010C3184, type=0
__DATA/__objc_catlist addr=0x010C7204, size=0x000000E0, fileOffset=0x010C3204, type=23
__DATA/__objc_protolist addr=0x010C72E4, size=0x00000094, fileOffset=0x010C32E4, type=0
__DATA/__objc_imageinfo addr=0x010C7378, size=0x00000008, fileOffset=0x010C3378, type=0
__DATA/__objc_const addr=0x010C7380, size=0x0002F690, fileOffset=0x010C3380, type=0
__DATA/__objc_selrefs addr=0x010F6A10, size=0x00002B30, fileOffset=0x010F2A10, type=14
__DATA/__objc_protorefs addr=0x010F9540, size=0x00000020, fileOffset=0x010F5540, type=0
__DATA/__objc_classrefs addr=0x010F9560, size=0x000004B0, fileOffset=0x010F5560, type=22
__DATA/__objc_superrefs addr=0x010F9A10, size=0x0000046C, fileOffset=0x010F5A10, type=0
__DATA/__objc_data addr=0x010F9E7C, size=0x00003A98, fileOffset=0x010F5E7C, type=0
__DATA/__objc_ivar addr=0x010FD914, size=0x000013C0, fileOffset=0x010F9914, type=0
__DATA/__cfstring addr=0x010FECD4, size=0x000065B0, fileOffset=0x010FACD4, type=16
__DATA/__data addr=0x01105290, size=0x00004864, fileOffset=0x01101290, type=0
__DATA/__objc_nlcatlist addr=0x01109AF4, size=0x00000010, fileOffset=0x01105AF4, type=0
__DATA/__common addr=0x01109B04, size=0x000004AC, fileOffset=0x00000000, type=24
__DATA/__bss addr=0x01109FB0, size=0x0000FFB4, fileOffset=0x00000000, type=24
ld: b/bl/blx thumb2 branch out of range (16777216 max is +/-16MB): from -AFHTTPSessionManager PATCH:parameters:success:failure: to _objc_release.island (0x00E087F0) in '-[AFHTTPSessionManager PATCH:parameters:success:failure:]' from /Users/egomez/Documents/my_apps/kaibigan_app/vendor/Pods/build-iPhoneOS/libPods.a(AFHTTPSessionManager.o) for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)
rake aborted!

Any ideas on what am doing wrong?

AFMotion fails

Hi,

I want to use AFMotion, but I keep getting this error:
http.rb:37:inparameter_encoding': uninitialized constant AFMotion::HTTP::AFFormURLParameterEncoding (NameError)`

This is how my Rakefile looks like:

# -*- coding: utf-8 -*-
$:.unshift('/Library/RubyMotion/lib')
require 'motion/project/template/ios'
require 'rubygems'
require 'bundler'
Bundler.require

Motion::Project::App.setup do |app|
  ...

  # Require AFNetworking
  app.pods do
    pod 'AFNetworking'
  end
end

And this is how my tasks.rb looks like:

  # When the view initializes, we need to load the data
  def on_load
    AFMotion::HTTP.get("http://google.com") do |result|
      p result.body
    end
  end

Any ideas?

Cheers.

Unable to find a specification for `AFNetworking (~> 2.0.1)` in new RM project

motion 2.19 with the following GemFile:

source "https://rubygems.org"

gem "rake"
gem "ProMotion", "~> 1.1.2"
gem "afmotion", "~> 2.0.0"

bundle install adds the following to GemFile.lock:

    afmotion (2.0.0)
      motion-cocoapods (~> 1.4.0)
      motion-require (~> 0.0.7)

Running "rake pod:install" results in the following error:

Resolving dependencies of
rake aborted!
[!] Unable to find a specification for `AFNetworking (~> 2.0.1)`.

Tasks: TOP => pod:install

I'm learning RubyMotion by way of the espn_app tutorial, and this is a very early stage: brand new app, ProMotion working fine, now just adding the afmotion dependency. Any help is appreciated.

How would you do something like this in afmotion?

headers = { 'Content-Type' => 'application/json' }
data = BW::JSON.generate({ user: {
                             email: "[email protected]",
                             password: "password"
                            } })

BW::HTTP.post("http://localhost:3000/api/v1/sessions.json", { headers: headers, payload: data } ) do |response|
    if response.ok?
      json = BW::JSON.parse(response.body.to_str)
    elsif response.status_code.to_s =~ /40\d/
      App.alert("Login failed")
    else
      App.alert(response.to_str)
    end
  end
end

Is it easily done with a one-off request or do I need to make a client?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.