Ios 如何在扩展中调用扩展中的函数
我需要做的是使用同样位于UIViewController扩展中的didSet从静态变量调用位于UIViewController扩展中的函数。下面是一些示例代码Ios 如何在扩展中调用扩展中的函数,ios,swift,Ios,Swift,我需要做的是使用同样位于UIViewController扩展中的didSet从静态变量调用位于UIViewController扩展中的函数。下面是一些示例代码 extension UIViewController { static var isWifiAvailable = false { didSet { if isWifiAvailable = true { getValidLogin()
extension UIViewController {
static var isWifiAvailable = false {
didSet {
if isWifiAvailable = true {
getValidLogin()
}
}
}
func getValidLogin() {
// do something
}
func otherFuncCallsit() {
isWifiAvailable = true
}
}
我试着用
DispatchQueue.main.async {
let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
if let topController = keyWindow?.rootViewController {
topController.getValidLogin(username: email, password: password, sender: "backgroundCheck")
}
}
但这导致我从getValidLogin调用的api无法工作。如果我使用这个解决方案,当我调用api时,session.uploadTask之后不会运行任何东西(例如print(“ok”)不会运行)。这是我的实际getValidLogin()(api的url已更改)
func getValidLogin(用户名:String,密码:String,发件人:String=”“){
让session=URLSession.shared
让url=url(字符串:“example.com”)!
var-request=URLRequest(url:url)
request.httpMethod=“POST”
request.setValue(“application/json”,forHTTPHeaderField:“Accept”)
request.setValue(“application/json”,forHTTPHeaderField:“Content Type”)
让json=[
“用户名”:用户名,
“密码”:密码
]
让jsonData=try!JSONSerialization.data(使用jsonObject:json,选项:[])
var done=false
让group=DispatchGroup()//初始化
打印(请求)
让task=session.uploadTask(with:request,from:jsonData){data,response,中的错误
group.enter()
如果数据==nil{
self.showNoWifiAlert()
loginResponseDetails.message=“由于Internet连接不稳定,无法登录。请重试”
小组请假()
完成=正确
}否则{
做{
guard let dictionary=将JSONSerialization.jsonObject(with:data!,options:[])作为?[String:Any]其他内容尝试{
打印(“无法将JSON内容转换为字典”)
返回
}
UIViewController.isWifiAvailable=true
loginResponseDetails.token=字典[“token”]作为字符串??“nil”
loginResponseDetails.message=字典[“message”]作为!字符串
loginResponseDetails.status=字典[“status”]as!Bool
loginResponseDetails.isResetFirstPassword=字典[“isResetFirstPassword”]as!Bool
loginResponseDetails.isFinalRegistrationSubmitted=字典[“isFinalRegistrationSubmitted”]as!Bool
loginResponseDetails.finalStatus=字典[“finalStatus”]作为?字符串??“nil”
loginResponseDetails.isAgreementsAccepted=字典[“isAgreementsAccepted”]as!Bool
loginResponseDetails.carrierCountry=字典[“carrierCountry”]作为?字符串??“nil”
打印(“令牌:+loginResponseDetails.token”)
打印(“消息:+loginResponseDetails.message”)
打印(“状态:+字符串(loginResponseDetails.status))
打印(“isResetFirstPassword:+字符串(loginResponseDetails.isResetFirstPassword))
打印(“isFinalRegistrationSubmitted:+字符串(loginResponseDetails.isFinalRegistrationSubmitted))
打印(“最终状态:+loginResponseDetails.finalStatus”)
打印(“isAgreementsAccepted:+字符串(loginResponseDetails.isAgreementsAccepted))
打印(“carrierCountry:+loginResponseDetails.carrierCountry)
小组请假()
完成=正确
}抓住{
//如果出现错误,则打印错误
打印(“错误:\(错误)”)
}
}
}
通知组(队列:.main){
task.resume()
}
重复{
RunLoop.current.run(直到:日期(timeIntervalSinceNow:0.1))
}好啦!完成了
打印(“确定”)
如果发送方==“背景检查”{
打印(loginResponseDetails.status)
打印(“确定”)
如果loginResponseDetails.status==true{
让vc=UIStoryboard(名称:“ShamitMain”,bundle:nil)
让navController=UINavigationController(rootViewController:vc)
navController.isNavigationBarHidden=false
navController.modalPresentationStyle=.fullScreen
self.present(导航控制器,动画:true,完成:nil)
}
}
}
那么,在使用上述解决方案时,是否有其他方法调用getValidLogin(),或者是否有任何方法可以解决我遇到的问题?使其成为非静态的。顺便说一句,如果您需要检查分机中@LeoDabus的网络状态,您可以在任何地方调用它。检查附加到post@LeoDabus哦,现在我显示你的编辑。很好。如果Network.reachability.status=.wifi
func getValidLogin(username: String, password: String, sender: String = "") {
let session = URLSession.shared
let url = URL(string: "example.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let json = [
"UserName": username,
"Password": password
]
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
var done = false
let group = DispatchGroup() // initialize
print(request)
let task = session.uploadTask(with: request, from: jsonData) { data, response, error in
group.enter()
if data == nil {
self.showNoWifiAlert()
loginResponseDetails.message = "Cannot Login Due to Unstable Internet Connection. Please Try again"
group.leave()
done = true
} else {
do {
guard let dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any] else {
print("Could not cast JSON content as a Dictionary<String, Any>")
return
}
UIViewController.isWifiAvailable = true
loginResponseDetails.token = dictionary["Token"] as? String ?? "nil"
loginResponseDetails.message = dictionary["Message"] as! String
loginResponseDetails.status = dictionary["Status"] as! Bool
loginResponseDetails.isResetFirstPassword = dictionary["IsResetFirstPassword"] as! Bool
loginResponseDetails.isFinalRegistrationSubmitted = dictionary["IsFinalRegistrationSubmitted"] as! Bool
loginResponseDetails.finalStatus = dictionary["FinalStatus"] as? String ?? "nil"
loginResponseDetails.isAgreementsAccepted = dictionary["IsAgreementsAccepted"] as! Bool
loginResponseDetails.carrierCountry = dictionary["CarrierCountry"] as? String ?? "nil"
print("token: " + loginResponseDetails.token)
print("message: " + loginResponseDetails.message)
print("status: " + String(loginResponseDetails.status))
print("isResetFirstPassword: " + String(loginResponseDetails.isResetFirstPassword))
print("isFinalRegistrationSubmitted: " + String(loginResponseDetails.isFinalRegistrationSubmitted))
print("finalStatus: " + loginResponseDetails.finalStatus)
print("isAgreementsAccepted: " + String(loginResponseDetails.isAgreementsAccepted))
print("carrierCountry: " + loginResponseDetails.carrierCountry)
group.leave()
done = true
} catch {
// Print error if something went wrong
print("Error: \(error)")
}
}
}
group.notify(queue: .main) {
task.resume()
}
repeat {
RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.1))
} while !done
print("ok")
if sender == "backgroundCheck" {
print(loginResponseDetails.status)
print("ok")
if loginResponseDetails.status == true {
let vc = UIStoryboard(name: "ShamitMain", bundle: nil).instantiateViewController(identifier: "LoginVC")
let navController = UINavigationController(rootViewController: vc)
navController.isNavigationBarHidden = false
navController.modalPresentationStyle = .fullScreen
self.present(navController, animated: true, completion: nil)
}
}
}