代码之家  ›  专栏  ›  技术社区  ›  user1233894

尝试从全局函数传递值

  •  0
  • user1233894  · 技术社区  · 5 月前

    我试图从另一个视图调用的函数传递一个Double值,该函数在AlamoFire请求完成之前返回一个值

    struct GetPrice {
    
        static func getThePrice(book: String) async -> Double? {
            
            var theNetPrice: Double = 0.0
            var iListPrice = ""
            let url = "https://example.com"
            
            let headers: HTTPHeaders = [
                "accept": "application/xml",
                "Authorization": "Basic \xxx",
               
                "Content-Type": "application/x-www-form-urlencoded"
            ]
    
            let body: [String: Any] = ["xxxxx"]
    
            AF.request(url, method: .post, parameters: body, encoding: URLEncoding.default, headers: headers)
                .responseData { response in
                var statusCode = response.response?.statusCode
                    //print("response.result ", response.result)
                switch response.result {
                case .success:
                    let data = response.data
                    let s = String(data: data!, encoding: .utf8)
                    let xml = XMLHash.parse(String(s!))
                    
                        iListPrice = xml["xxx"].element!.text
                        theNetPrice = Double(iListPrice)
                        print(theNetPrice) // this shows correct value
                        //return theNetPrice -- this would give error 'Cannot convert value of type 'Double' to closure result type 'Void''
                case .failure(let error):
                    statusCode = error._code
                    print("status code is: \(String(describing: statusCode))")
                    
                    print(error)
                }
            }
            
            return theNetPrice //returns 0.0
        }
    }
    '''
    
    1 回复  |  直到 5 月前
        1
  •  0
  •   workingdog support Ukraine    5 月前

    尝试使用以下方法 continuation 如示例代码所示。

    struct GetPrice {
    
        static func getThePrice(book: String) async -> Double? {
            //..
            return await withCheckedContinuation { continuation in
                AF.request(url, method: .post, parameters: body, encoding: URLEncoding.default, headers: headers)
                    .responseData { response in
                        var statusCode = response.response?.statusCode
                        //print("response.result ", response.result)
                        switch response.result {
                        case .success:
                            let data = response.data
                            let s = String(data: data!, encoding: .utf8)
                            let xml = XMLHash.parse(String(s!))
                            
                            iListPrice = xml["xxx"].element!.text
                            theNetPrice = Double(iListPrice)
                            print(theNetPrice) // this shows correct value
    
                            continuation.resume(returning: theNetPrice)
    
                        case .failure(let error):
                            statusCode = error._code
                            print("status code is: \(String(describing: statusCode))")
                            print(error)
    
                            continuation.resume(returning: theNetPrice)
    
                        }
                    }
            }
    
        }
    }
    

    用它来做类似的事情

     Task {
         let price = await GetPrice.getThePrice(book: "MyBook")
         if let price = price {
             print("The price is: \(price)")
         }
     }
    

    或者,您可以尝试使用完成处理程序,例如

     static func getThePrice(book: String, completion: @escaping (Double?) -> Void) {
         //..
             AF.request(url, method: .post, parameters: body, encoding: URLEncoding.default, headers: headers)
                 .responseData { response in
                     var statusCode = response.response?.statusCode
                     //print("response.result ", response.result)
                     switch response.result {
                     case .success:
                         let data = response.data
                         let s = String(data: data!, encoding: .utf8)
                         let xml = XMLHash.parse(String(s!))
                         
                         iListPrice = xml["xxx"].element!.text
                         theNetPrice = Double(iListPrice)
                         print(theNetPrice) // this shows correct value
                         
                        completion(theNetPrice)
     
                     case .failure(let error):
                         statusCode = error._code
                         print("status code is: \(String(describing: statusCode))")
                         print(error)
     
                        completion(theNetPrice)
    
                     }
                 }
         }
    

    这样使用它:

     GetPrice.getThePrice(book: "MyBook") { price in
             if let price = price {
                 print("The price is: \(price)")
             }
         }