首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >同步请求的信号量Swift4永远停止

同步请求的信号量Swift4永远停止
EN

Stack Overflow用户
提问于 2018-03-21 12:41:56
回答 1查看 108关注 0票数 0

我需要来自web服务的同步请求,所以我使用sempahore:

代码语言:javascript
复制
class func syncProducts() {
    print("syncProducts() 1")
    let idsLocal = getProductsIds()
    let semaphore = DispatchSemaphore(value: 0)
    var idsCloud : [Int] = []
    print("Getting cloud ids... 1")

    OdooService.getProductsIds { (params: [Int]) in
        print("SuccessBlock size ids: \(params.count)  1")
        idsCloud = params
        semaphore.signal()
    }

    semaphore.wait()
    print("Depois do GetproductsIds:  1")
}

但是在这个例子中,应用程序永远保持锁!请求永远不会结束。这是我从and服务器请求数据的功能,如果是这样的话,返回到成功块。

代码语言:javascript
复制
static func getProductsIds(successBlock: @escaping (_ params: [Int]) -> Void)  {
    // check odoo auth
    let dispatch = DispatchGroup()
    if( OdooAuth.uid == 0 ) {
        print("Odoo offline, tentando reconectar...")
        dispatch.enter()
        OdooAuth.reconnect(successBlock: { params in
            print("Reconectado com sucesso...")
            dispatch.leave()
        }, failureBlock: { params in
            print("Falha no ReAuth")
            return
        })
    }

    print("Start request from Odoo...")
    let fieldsProducts = ["id"]
    let options = [ "fields": fieldsProducts] as [String : Any]
    var idsList : [Int] = []
    let params = [OdooAuth.db, OdooAuth.uid, OdooAuth.password,"product.template","search_read",[],options] as [Any]

    AlamofireXMLRPC.request(OdooAuth.host2, methodName: "execute_kw", parameters: params).responseXMLRPC {
        (response: DataResponse<XMLRPCNode>) -> Void in
        switch response.result {
        case .success( _):
            print("Success to get Ids")
            let str = String(data: response.data!, encoding: String.Encoding.utf8) as String!
            let options = AEXMLOptions()
            let xmlDoc = try? AEXMLDocument(xml: (str?.data(using: .utf8))!,options: options)
            //print(xmlDoc!.xml)

            for child in (xmlDoc?.root["params"]["param"]["value"]["array"]["data"].children)! {
                for childValue in child["struct"].children {
                    let id = childValue["value"]["int"].value!
                    idsList.append(Int(id)!)
                    //print("Id: \(id)")
                }
            }

            successBlock(idsList)

            break

        case .failure(let error):
                print("Error to get Ids: \(error.localizedDescription)")
            break
        } // fim switch
    } // fim request
} // fim getProductsIds

我不知道信号量是否是最好的方法,但我需要同步请求!我试过使用DispatchGroup(),就像在reauth中一样,但也不起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-21 12:58:37

我预计死锁是在主线程上调用getProductsIds回调的结果,该回调被信号量阻塞。据我所知,默认情况下,Alamofire会在主线程上分配回调,我认为这是AlamofireXMLRPC的情况,因为它是Alamofire的包装器。

我强烈建议在异步操作期间不要阻塞主线程。

但是,如果出于任何真正好的理由,您不能这样做,则需要确保回调不会被分派到主调度队列上(因为该队列在等待信号时被阻塞)。Alamofire本身有一个response重载,允许指定要在其上运行回调的DispatchQueue对象。AlamofireXMLRPC似乎也有一个,所以我会尝试利用它来改变

代码语言:javascript
复制
AlamofireXMLRPC.request(OdooAuth.host2, methodName: "execute_kw", parameters: params)
               .responseXMLRPC {
     // process result
}

至:

代码语言:javascript
复制
AlamofireXMLRPC.request(OdooAuth.host2, methodName: "execute_kw", parameters: params)
               .responseXMLRPC(queue: DispatchQueue.global(qos: .background)) {
     // process result
}

我基于github 源代码 of AlamofireXMLRPC,但以前没有使用过它,所以可能会出现一些语法错误。但它应该会指引你走向正确的方向。尽管如此,我还是建议您不要阻止线程(我在重复自己,但这确实是非常重要的一点)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49406624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档