Search code examples
swiftasynchronousrequestgrand-central-dispatchalamofire

Swift - Grand Central Dispatch Class


I work on a central point(class), where my data is requested and retrieved.

This class can be called from any view:

override func viewDidLoad() {
    super.viewDidLoad()

    let group = dispatch_group_create()
    var data = RestApiManager(group)
    dispatch_group_notify(group, dispatch_get_main_queue()) {
        return data
    }
}

class RestApiManager {

    let user = "user"
    let password = "password"

    var result: JSON = []

    init(group) {

        dispatch_group_enter(group)
        Alamofire.request(.GET, "http://example.com/api/")
            .authenticate(user: user, password: password)
            .responseJSON { _, _, result in
                switch result {
                case .Success(let data):
                    self.result[] = JSON(data)
                case .Failure(_, let error):
                    print("Request failed with error: \(error)")
                }
                dispatch_group_leave(group)
        }
    }
}

But it already fails when initializing the class.

Anybody could help me to design this a proper way??

Thanks and Greetings


Solution

  • import XCPlayground
    
    XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
    
    import Foundation
    
    class C {
        var txt: String = "start"
        init(group: dispatch_group_t) {
            dispatch_group_enter(group)
            print(txt)
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
                usleep(200000)
                self.txt = "end"
                print(self.txt)
                dispatch_group_leave(group)
            }
        }
    }
    
    func f() {
        let group = dispatch_group_create()
        let c = C(group: group)
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("notify: \(c) created")
        }
    }
    
    f()
    print("continue running ...")
    

    This works for me without any trouble. You wrote "But it already fails when initializing the class." What does it means exactly? Explain your 'failure' in details ... By the way, I don't understand how do you return your data (return data) from group notification handler ... (generally from any asynchronous code)