苹果文档
1.通常都是使用Reachability来检查网络状态的:Reachability github链接
可以获取是wifi还是3G网络,但此库依据查看有没有ip地址,这就造成了连上wifi,但是wifi上不了网的情况下,依然返回网络可连接的结果
2.使用NSURLRequest简单的判断:
/**
* 检测网络是否连接
*/
func requestUrl(urlString:String) -> Bool {
let url:NSURL =NSURL(string: urlString)!
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.timeoutInterval =5
var response:NSURLResponse?
do {
tryNSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
iflet httpResponse = responseas?NSHTTPURLResponse {
if httpResponse.statusCode ==200 {
print("response:\(httpResponse.statusCode)")
returntrue
}else {
//do something like a note
print("请打开网络设置,确保设备联网")
}
}
returnfalse
}
catch (let error) {
print("error:\(error)")
returnfalse
}
}
3. 将两者结合: