Class: AFMotion::SessionObserver

Inherits:
Object
  • Object
show all
Defined in:
lib/afmotion/client_shared.rb

Overview

Instance Method Summary collapse

Constructor Details

#initialize(task, callback) ⇒ SessionObserver

Returns a new instance of SessionObserver.



5
6
7
8
9
# File 'lib/afmotion/client_shared.rb', line 5

def initialize(task, callback)
  @callback = callback
  task.addObserver(self, forKeyPath:"state", options:0, context:nil)
  task.addObserver(self, forKeyPath:"countOfBytesSent", options:0, context:nil)
end

Instance Method Details

#observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/afmotion/client_shared.rb', line 11

def observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
  if keyPath == "countOfBytesSent"
    # Could be -1, see https://github.com/AFNetworking/AFNetworking/issues/1354
    expectation = (object.countOfBytesExpectedToSend > 0) ? object.countOfBytesExpectedToSend.to_f : nil
    @callback.call(nil, object.countOfBytesSent.to_f, expectation)
  end

  if keyPath == "state" && object.state == NSURLSessionTaskStateCompleted
    begin
      object.removeObserver(self, forKeyPath: "state")
      object.removeObserver(self, forKeyPath: "countOfBytesSent")
      @callback = nil
    rescue
    end
  end
end