iam试图从ecplogin中的开关statment返回响应主体,但它给了我这个错误" void中的意外非流动返回值",即使我声明函数gotourl(( ->第33行中的字符串。请建议。
这是我的代码
import UIKit
import SwiftECP
import XCGLogger
class ViewController: UIViewController {
@IBOutlet var UsernameField: UITextField!
@IBOutlet var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func _Login(_ sender: Any) {
self.gotourl()
// performSegue(withIdentifier: "gotowelcome", sender: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func gotourl() -> String{
let username: String = UsernameField.text!
let password: String = passwordField.text!
let protectedURL = URL(
string: "https://itsapps.odu.edu/auth/getInfo.p"
)!
let logger = XCGLogger()
logger.setup(level: .debug)
ECPLogin(
protectedURL: protectedURL,
username: username,
password: password,
logger: logger
).start { event in
switch event {
case let .value( body) :
// If the request was successful, the protected resource will
// be available in 'body'. Make sure to implement a mechanism to
// detect authorization timeouts.
print("Response body: (body)")
return body
// The Shibboleth auth cookie is now stored in the sharedHTTPCookieStorage.
// Attach this cookie to subsequent requests to protected resources.
// You can access the cookie with the following code:
if let cookies = HTTPCookieStorage.shared.cookies {
let shibCookie = cookies.filter { (cookie: HTTPCookie) in
cookie.name.range(of: "shibsession") != nil
}[0]
print(shibCookie)
}
case let .failed(error):
// This is an AnyError that wraps the error thrown.
// This can help diagnose problems with your SP, your IdP, or even this library :)
switch error.cause {
case let ecpError as ECPError:
// Error with ECP
// User-friendly error message
print(ecpError.userMessage)
// Technical/debug error message
print(ecpError.description)
case let alamofireRACError as AlamofireRACError:
// Error with the networking layer
print(alamofireRACError.description)
default:
print("Unknown error!")
print(error)
}
default:
break
}
}
}
}
我想返回的这部分
case let .value( body) :
// If the request was successful, the protected resource will
// be available in 'body'. Make sure to implement a mechanism to
// detect authorization timeouts.
print("Response body: (body)")
return body
那么有办法解决吗?谢谢
return
不会从gotourl()
返回。它正在从您传递给ECPLogin
的关闭中返回。从您的代码和错误消息中看来,您调用的方法将完成为最后一个参数,并且期望此封闭不会返回值(即,它返回Void
(。这就是为什么您会遇到错误的原因 - 当闭合应该什么都没有返回时,您将返回字符串。看起来您正在使用的ECPLogin
函数是异步的,这意味着它不会立即产生结果,而是完成一些工作并在完成后调用闭合。
您的代码不会从gotourl()
返回任何内容,这将是另一个问题,与此相关。
如何修复它取决于您的应用需要如何工作。一些选项包括:
- 更改
gotourl()
,以便完成完成闭合而不是返回值。然后用称呼此关闭的皮棉替换您的return
。 - 使用派遣组之类的东西使您的代码等到
ECPLogin
调用完成,然后以这种方式返回值。 - 使用其他选项,以便您不需要等到字符串可用,例如发布通知。