Reactive Programming with Swift by Cecil Costa

Reactive Programming with Swift by Cecil Costa

Author:Cecil Costa [Costa, Cecil]
Language: eng
Format: azw3
Publisher: Packt Publishing
Published: 2016-04-28T04:00:00+00:00


Implementing the genre signal

Finally, we have to create the getGenreSignal function, which was used in the previous section. Here, as we know, this is a private function that returns a RACSignal and it will do a request to a specific URL; thus, we can start opening this function with the following code:

private func getGenreSignal() -> RACSignal { let url = NSURL(string: "https://api.themoviedb.org/3/genre/movie/list?api_key=\(self.apiKey)")!

Continue creating a signal, which is the one that will be returned, and using the NSURLSession for requesting the genre list with the following code:

return RACSignal.createSignal({ (subscriber: RACSubscriber!) -> RACDisposable! in let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data:NSData?, response: NSURLResponse?, error: NSError?) -> Void in

Once the request is done, we have to validate it. We can use the guard statement for controlling the input:

guard error == nil else { subscriber.sendError(error!) return } guard let data = data else { subscriber.sendError(NSError(domain: "app", code: 1, userInfo: nil)) return }

Finally, we can convert the received data into a Swift object (or objects); remember that this conversion can still fail, which will make us trap this error and send it as a signal error rather than propagating it as an exception:

do { let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) subscriber.sendNext(json) subscriber.sendCompleted() }catch let raisedError as NSError { subscriber.sendError(raisedError) } } // end dataTaskWithURL

As you know, a data task doesn't do anything without calling the resume method, and we all agree that it is a good time for doing this:

task.resume()

Finally, we can return the disposable that is required by the function definition. In this case, we have to cancel the request that is being done. After that, this function is done:

return RACDisposable(block: { () -> Void in task.cancel() }) }) } // end getGenreSignal } // end MovieDetailViewController

This View Controller is already done; however, as you can see, it requires some information that need to be sent from the first scene to the second one.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.