Swift:按顺序发出多个异步请求。如何等待先前的请求完成?

时间:2017-01-02 14:27:37

标签: swift api http facebook-graph-api asynchronous

作为我的应用程序中身份验证过程的一部分,用户可以使用他们的Facebook帐户登录 - 我正在使用Facebook iOS SDK来处理此过程。验证完成后,我向Facebook图形api发出请求以获取用户配置文件数据(这是第一个异步请求)。第二个异步请求也是Facebook图形api,以请求安装了应用程序的用户朋友列表。

此函数中的最后和第三个请求向我开发的API发出异步POST请求,以发布从Facebook收集的所有数据。最后,一旦完成,用户就可以进入应用程序。然而事实并非如此,似乎Facebook请求在对API的POST请求之前没有完成,因此推送空白数据。我不介意Facebook的前2个请求按什么顺序完成,但是我需要在允许用户访问应用程序之前将数据成功发布到API。我尝试过使用信号量和Dispatch组,但是在查看控制台时,事情并没有以正确的顺序运行,我可以从API数据库中看到正在插入空值。

身份验证控制器

 // Successful login, fetch faceook profile
            let group = DispatchGroup()
            group.enter()
            // Redirect to tab bar controller should not happen until fetchProfile() has finished 
            // Redirect should not happen if fetchProfile() errors
            self.fetchProfile() 
            group.leave()

            // Redirect to tab bar controller
            let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let tabBarController = storyboard.instantiateViewController(withIdentifier: "tabBarController") as! UITabBarController
            self.present(tabBarController, animated: true, completion: nil)

更新了Facebook抓取资料

// Facebook Profile Request
func fetchProfile() {

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
let user = appDelegate.user
var facebookFriends = [String?]()

do {
    let results = try managedContext?.fetch(fetchRequest)
    fetchedUser = results![0] as? NSManagedObject
}
catch {
    print("Error fetching User entity")
    return
}


let group = DispatchGroup()
print("Starting Step 1")
group.enter()

// Facebook Profile
let parameters = ["fields": "id, email, first_name, last_name, picture.width(500).height(500), birthday, gender"]
FBSDKGraphRequest(graphPath: "me", parameters: parameters).start { (connection, result, error) -> Void in

    if error != nil {
        print(error)
        return
    }

    let result = result as? NSDictionary

    if let providerID = result?["id"] as? String {
        user.provider_id = providerID
        self.fetchedUser!.setValue(providerID, forKey: "provider_id")
    }

    if let firstName = result?["first_name"] as? String {
        user.first_name = firstName
        self.fetchedUser!.setValue(firstName, forKey: "first_name")
    }

    if let lastName = result?["last_name"] as? String {
        user.last_name = lastName
        self.fetchedUser!.setValue(lastName, forKey: "last_name")
    }

    if let email = result?["email"] as? String {
        user.email = email
        self.fetchedUser!.setValue(email, forKey: "email")
    }

    if let picture = result?["picture"] as? NSDictionary, let data = picture["data"] as? NSDictionary, let url = data["url"] as? String {
        user.avatar = url
        self.fetchedUser!.setValue(url, forKey: "avatar")
    }

    if let birthday = result?["birthday"] as? String {
        user.birthday = birthday
        self.fetchedUser!.setValue(sqlDate, forKey: "birthday")
    }

    if var gender = result?["gender"] as? String {
        user.gender = gender
        self.fetchedUser!.setValue(gender, forKey: "gender")
    }

    group.leave()
    print("Step 1 Done")

    group.enter()
    print("Starting Step 2")

    // Facebook Friends Request
    FBSDKGraphRequest(graphPath: "me/friends", parameters: ["fields": "id, first_name, last_name, picture"]).start { (connection, result, error) -> Void in

        if error != nil {
            print(error)
            return
        }

        let result = result as! [String:AnyObject]

        for friend in result["data"] as! [[String:AnyObject]] {
            let id = friend["id"] as! String
            facebookFriends.append(id)
        }

        group.leave()
        print("Step 2 Done")

        // User POST Request
        var dictionary = self.fetchedUser?.dictionaryWithValues(forKeys: ["provider", "provider_id", "first_name", "last_name", "email", "avatar", "birthday", "gender"])

        if facebookFriends.count > 0 {
            dictionary?["friends"] = facebookFriends
        }

        let data = NSMutableDictionary()
        data.setValuesForKeys(dictionary!)

        //let semaphore = DispatchSemaphore(value: 2)
        group.enter()
        print("Starting Step 3")

        do {
            // Here "jsonData" is the dictionary encoded in JSON data
            let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)

            // Here "decoded" is of type `Any`, decoded from JSON data
            let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])

            // Final dict
            if let dictFromJSON = decoded as? [String:String] {

                let endpoint = "http://endpoint.com/user"
                let url = URL(string: endpoint)
                let session = URLSession.shared
                var request = URLRequest(url: url!)

                request.httpMethod = "POST"
                request.httpBody = try JSONSerialization.data(withJSONObject: dictFromJSON, options: [])
                request.addValue("application/json", forHTTPHeaderField: "Accept")
                request.addValue("application/json", forHTTPHeaderField: "Content-Type")
                session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in

                    if error != nil {
                        //semaphore.signal()
                        group.leave()
                        print(error)
                        return
                    }

                    do {
                        // Save response
                        let json = try(JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: AnyObject])

                        if let userID = json?["user_id"] {
                            user.user_id = userID as? Int
                            self.fetchedUser!.setValue(userID, forKey: "user_id")
                        }

                        if let friends = json?["friends"] , !(friends is NSNull){
                            user.friends = friends as? [String]
                            self.fetchedUser!.setValue(friends, forKey: "friends")
                        }

                        group.leave()
                        //semaphore.signal()

                    } catch let jsonError {
                        print(jsonError)
                        return
                    }

                }).resume()

            }
        } catch {
            print(error.localizedDescription)
        }

        // Wait to async task to finish before moving on
        //_ = semaphore.wait(timeout: DispatchTime.distantFuture)
        print("Step 3 Done")
    }
}

}

1 个答案:

答案 0 :(得分:1)

在闭包本身内的每个闭包之后移动代码,以便在运行之前等待它之前的代码:

// Facebook Profile Request
func fetchProfile() {

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
    let user = appDelegate.user
    var facebookFriends = [String?]()

    do {
        let results = try managedContext?.fetch(fetchRequest)
        fetchedUser = results![0] as? NSManagedObject
    }
    catch {
        print("Error fetching User entity")
        return
    }


    let group = DispatchGroup()
    print("Starting Step 1")
    group.enter()

    // Facebook Profile
    let parameters = ["fields": "id, email, first_name, last_name, picture.width(500).height(500), birthday, gender"]
    FBSDKGraphRequest(graphPath: "me", parameters: parameters).start { (connection, result, error) -> Void in

        if error != nil {
            print(error)
            return
        }

        let result = result as? NSDictionary

        if let providerID = result?["id"] as? String {
            user.provider_id = providerID
            self.fetchedUser!.setValue(providerID, forKey: "provider_id")
        }

        if let firstName = result?["first_name"] as? String {
            user.first_name = firstName
            self.fetchedUser!.setValue(firstName, forKey: "first_name")
        }

        if let lastName = result?["last_name"] as? String {
            user.last_name = lastName
            self.fetchedUser!.setValue(lastName, forKey: "last_name")
        }

        if let email = result?["email"] as? String {
            user.email = email
            self.fetchedUser!.setValue(email, forKey: "email")
        }

        if let picture = result?["picture"] as? NSDictionary, let data = picture["data"] as? NSDictionary, let url = data["url"] as? String {
            user.avatar = url
            self.fetchedUser!.setValue(url, forKey: "avatar")
        }

        if let birthday = result?["birthday"] as? String {
            user.birthday = birthday
            self.fetchedUser!.setValue(sqlDate, forKey: "birthday")
        }

        if var gender = result?["gender"] as? String {
            user.gender = gender
            self.fetchedUser!.setValue(gender, forKey: "gender")
        }

        group.leave()
        print("Step 1 Done")

        group.enter()
        print("Starting Step 2")

        // Facebook Friends Request
        FBSDKGraphRequest(graphPath: "me/friends", parameters: ["fields": "id, first_name, last_name, picture"]).start { (connection, result, error) -> Void in

            if error != nil {
                print(error)
                return
            }

            let result = result as! [String:AnyObject]

            for friend in result["data"] as! [[String:AnyObject]] {
                let id = friend["id"] as! String
                facebookFriends.append(id)
            }

            group.leave()
            print("Step 2 Done")

            // User POST Request
            var dictionary = self.fetchedUser?.dictionaryWithValues(forKeys: ["provider", "provider_id", "first_name", "last_name", "email", "avatar", "birthday", "gender"])

            if facebookFriends.count > 0 {
                dictionary?["friends"] = facebookFriends
            }

            let data = NSMutableDictionary()
            data.setValuesForKeys(dictionary!)

            //let semaphore = DispatchSemaphore(value: 2)
            group.enter()
            print("Starting Step 3")

            do {
                // Here "jsonData" is the dictionary encoded in JSON data
                let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)

                // Here "decoded" is of type `Any`, decoded from JSON data
                let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])

                // Final dict
                if let dictFromJSON = decoded as? [String:String] {

                    let endpoint = "http://endpoint.com/user"
                    let url = URL(string: endpoint)
                    let session = URLSession.shared
                    var request = URLRequest(url: url!)

                    request.httpMethod = "POST"
                    request.httpBody = try JSONSerialization.data(withJSONObject: dictFromJSON, options: [])
                    request.addValue("application/json", forHTTPHeaderField: "Accept")
                    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
                    session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in

                        if error != nil {
                            //semaphore.signal()
                            group.leave()
                            print(error)
                            return
                        }

                        do {
                            // Save response
                            let json = try(JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: AnyObject])

                            if let userID = json?["user_id"] {
                                user.user_id = userID as? Int
                                self.fetchedUser!.setValue(userID, forKey: "user_id")
                            }

                            if let friends = json?["friends"] , !(friends is NSNull){
                                user.friends = friends as? [String]
                                self.fetchedUser!.setValue(friends, forKey: "friends")
                            }

                            group.leave()
                            //semaphore.signal()

                        } catch let jsonError {
                            print(jsonError)
                            return
                        }

                    }).resume()

                }
            } catch {
                print(error.localizedDescription)
            }

            // Wait to async task to finish before moving on
            //_ = semaphore.wait(timeout: DispatchTime.distantFuture)
            print("Step 3 Done")
        }
    }
}

说明:当您执行异步Web请求时,闭包是所谓的转义,这意味着它们在函数返回后运行。例如,FBSDKGraphRequest.start采用转义闭包,保存,返回,返回后,在请求完成后运行闭包。这是故意的。否则,它会同步并阻止您的代码,这会导致您的应用程序冻结(除非您使用GCD自己异步运行代码)。

TL; DR在FBSDKGraphRequest.start之类的函数返回后调用闭包,导致下一个组在完成之前启动。这可以通过放置它们以便它们一个接一个地运行来修复。