等待函数在Swift中完成

时间:2015-12-09 19:22:12

标签: ios swift asynchronous

我有一个问题 我正在使用图形数据库。对于每个用户,我想将一个艺术家列表写入数据库。 我调用了我的saveProfileData,现在应该将Artist逐个添加到数据库中。但是,在调用addArtistsToDatabase之后,不会调用executeCypher方法(来自另一个api),但是一段时间之后。因此,并非所有艺术家都被写入数据库。我想实现我的方法,对于每个艺术家,实际的艺术家被写入数据库,并等待直到完成。我对Swift很新,不知道如何解决这个问题。

func saveProfileData(){
    let p = self.profile
    ...
        //add Artists
        for a:Artist in p.artists{
            self.addArtistToDatabase(a)
        }
}

func addArtistToDatabase(a: Artist){

    let cyperQuery: String = "MATCH (a:Artist) WHERE a.id IN [\"\(a.id)\"] RETURN a"
    let cyperParams: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()

    client.executeCypher(cyperQuery, params: cyperParams, completionBlock: {(cypher, error) in
        print("response from cyper \(cypher)")
        //check if result is empty
        let response = cypher?.data

        var isEmpty: Bool = false
        if((response?.count) == 0){
            isEmpty = true
        }
        if(isEmpty){
            //if so create new node for each artist and add the relationhip between artist and user
            let cyperQuery1: String = "CREATE (n:Artist {id:\"\(a.id)\", name:\"\(a.name)\"})"
            let cyperParams1: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
            self.client.executeCypher(cyperQuery1, params: cyperParams1, completionBlock: {(cypher, error) in
                print("response from cyper \(cypher)")
            })

            let query: String = "MATCH (a:User),(b:Artist) WHERE a.id=\"\(self.profile.id)\" AND b.id=\"\(a.id)\" CREATE (a)-[r:ListenTo {interested: \"\(a.display)\"}]->(b) RETURN r "
            let params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
            self.client.executeCypher(query, params: params, completionBlock: {(cypher, error) in
                print("response from cyper \(cypher)")
            })

        }else{
            //update relationship
            let query: String = "MATCH (n:User {id:\"\(self.profile.id)\"})-[r:ListenTo]->(a:Artist {id:\"\(a.id)\"}) SET r.interested = \"\(a.display)\" RETURN r"
            let params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
            self.client.executeCypher(query, params: params, completionBlock: {(cypher, error) in
                print("response from cyper \(cypher)")
            })
        }
    })

}

0 个答案:

没有答案