Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

How to wait for NSURLSession dataTaskWithRequest before returning from function

ryantcbryantcb Posts: 667Registered Users @ @ @
edited July 2015 in iOS SDK Development
I have a function from which I wish to return a String. The function goes off and in the background gets some JSON a value from which i return the String. Trouble is I hit the return before the value is retrieved. How can I wait for the NSURLSessions dataTaskWithRequest to finish before returning?

[code]func getProfileInfoForYouTubeUser(userName : String, APItype : String, partParameter : String) -> String {

let url = NSURL(string: "https://www.google...")!

let request = NSURLRequest(URL: url)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(data, response, error) -> Void in
if error == nil{

try! self.youTubeResponseDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as! NSDictionary

//use self.youTubeResponseDictionary to find value for youtubeChannelURL

}
else{
print("erro \(error?.localizedDescription)")
}
}
task.resume()

return youtubeChannelURL

}[/code]
p.s why are the code tags not working?
Post edited by ryantcb on

Replies

  • baja_yubaja_yu San FranciscoPosts: 6,215Moderators, Registered Users Admin
    The whole point of background tasks and asynchronous requests is that they're not blocking. I suggest looking into the KSPromise library (https://github.com/kseebaldt/deferred) which will allow you to nicely manage the flow by passing success and error blocks which will get called when the promise is resolved.
  • ryantcbryantcb Posts: 667Registered Users @ @ @
    Appreciated
  • C6Silver05C6Silver05 SeattlePosts: 632New Users @ @ @
    NSNoticationCenter. You make a web service call and when the web service returns you use the notification center to alert the portion of the app that cares and execute the method you require. Use the userInfo portion of the post to send any needed data to the method that is listening.
  • baja_yubaja_yu San FranciscoPosts: 6,215Moderators, Registered Users Admin
    Please don't use NSNotificationCenter, at least not for this use case. If possible, forget that it exists at all. Here's a short article on a few reasons why: https://objcsharp.wordpress.com/2013/08/28/why-nsnotificationcenter-is-bad/
  • C6Silver05C6Silver05 SeattlePosts: 632New Users @ @ @
    baja_yu wrote: »
    Please don't use NSNotificationCenter, at least not for this use case. If possible, forget that it exists at all. Here's a short article on a few reasons why: https://objcsharp.wordpress.com/2013/08/28/why-nsnotificationcenter-is-bad/

    An interesting article to be sure. However, I am not convinced that it shouldn't ever be used (neither is the author who states it should be used "sparingly"). Like everything else it can be abused; however, I am not convinced it isn't a clean way to handle asynch server events. Additionally, one can use "object" to interrogate the source and make sure that the receiver should process it. One can also use "userInfo" to inspect data that can also be structured to ensure proper and approved handling. The article offers food for thought and I want to take another pass over it but I am not seeing a reason to completely throw out this pattern that Apple has provided in favor of 3rd party code or more esoteric handling (at least not yet).

  • baja_yubaja_yu San FranciscoPosts: 6,215Moderators, Registered Users Admin
    Right. It does have a purpose. However, handling async network request responses is not one of them. Any object can register to receive notifications for a certain key. Even worse, any object can send notifications for that same key. That means Object A can send an event with your object, and have Object B, C, Z, XYZ receive it, when maybe B was the only one that should do it. Even worse, Object X can send an event, and B would receive it while it was waiting for an event from Object A. There is also no guarantee that anyone is listening, which is probably not something you want when making network request. Concept of promises has been around for decades, it is hardly esoteric. They also make writing tests much easier.

  • C6Silver05C6Silver05 SeattlePosts: 632New Users @ @ @
    To me everything presented can easily be controlled. From interrogating the object to the data structure that is passed. However, I would quickly add that this is in the context of a developer and not of a team. Perhaps the issues mentioned are a bigger challenge and more apparent if we are talking a team of people working on a single app. As a single developer working on app these issues are either very remote or have to be the result of very sloppy work. When you post or receive you have to give it a very specific name and again even an object if you want to go further with that notion. Then you have to consume the data structure that comes with it (I am assuming there is a data expectation here) and of course to consume that data it has to be of a specific structure. I am having a very hard time seeing how to screw this up although again I can understand the dynamics would be more complicated if we are talking a team of people.

    Frankly the biggest issue I see with notifications is properly removing yourself as an observer. Not doing so can cause the observer to fire multiple times. I am not sure of the case for a single observer to need to observe the same event more than once at a time but Apple allows it. Again not property removing/adding yourself is the real risk I have seen with this approach.

    I do appreciate the alternative approach as I will admit it never occurred me to do it any other way. Notifications are so simple and native that this isn't something I would have considered so I appreciate the edification.
  • baja_yubaja_yu San FranciscoPosts: 6,215Moderators, Registered Users Admin
    Sloppy code is sloppy code regardless of how many people are maintaining the codebase.

    I would recommend grabbing "Clean Code" by Uncle Bob. There are also a number of YouTube videos on SOLID design principles by Uncle Bob and Sandi Metz that are really worth a watch.

    You can also look at this repo on github https://github.com/cbguder/BestPractices which illustrates some of the best practices with Objective C, including dependency injection, promises, TDD, etc.
  • C6Silver05C6Silver05 SeattlePosts: 632New Users @ @ @
    @baja_yu Thanks for the links and recommendations. I will check those out.
Sign In or Register to comment.