在Swift中基于超时创建函数

问题描述

我想创建一个在相当长的时间内返回内容的函数。如果超时,该函数应返回一些预定义的值。例如,

func loginFunc(timeOut: Int) {
        
    Login.getUSerAuthenticaiton(email: "abc@zyf.com",password: "123456789",completion: {_,_ in 
            print("Reponse")
    })
}

调用函数之类的

loginFunc(timeOut: 10)

意味着,该函数应运行10秒钟,然后返回nil。确保这将是API调用或正常的功能。

解决方法

第一种方式:

 let timer = Timer.scheduledTimer(withTimeInterval: 10,repeats: false) { timer in
       print("Time is Over")
    }
    Login.getUSerAuthenticaiton(email: "abc@zyf.com",password: "123456789",completion: {_,_ in
            print("Reponse")
        timer.invalidate()
    })

如果响应速度超过10秒并且计时器回调从未触发,您可以使计时器无效

第二种方式:

func loginFunc(timeOut: Int) {
    
    var isResponseGet = false
    
    let timer = Timer.scheduledTimer(withTimeInterval: 10,repeats: false) { timer in
        if isResponseGet {
            print("<##>Already get a rtesponse")
        } else {
            print("10 secs left and i didn't get a response")
        }
    }
    Login.getUSerAuthenticaiton(email: "abc@zyf.com",_ in
            print("Reponse")
        isResponseGet = true
    })
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...