Swift를 사용하여 인터넷 연결이 가능한지 확인하는 방법이 있습니까?
이를 수행하는 많은 타사 라이브러리가 있지만 모두 Objective-C로 작성되었습니다. Swift 대안을 찾고 있습니다.
답변
의견에서 언급했듯이 Swift에서 Objective-C 라이브러리를 사용할 수 있지만 더 순수한 Swift 솔루션을 원했습니다. 기존 Apple Reachability 클래스 및 기타 타사 라이브러리는 Swift로 번역하기에는 너무 복잡해 보였습니다. 좀 더 Google을 검색 했고 네트워크 가용성을 확인하는 간단한 방법을 보여주는 이 기사 를 보았습니다. 나는 이것을 Swift로 번역하기 시작했습니다. 나는 많은 걸림돌을 겪었 지만 StackOverflow의 Martin R 덕분에 그것들을 해결할 수 있었고 마침내 Swift에서 실행 가능한 솔루션을 얻었습니다. 다음은 코드입니다.
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return isReachable && !needsConnection
}
}
Swift> 3.0의 경우
public class Reachability {
public func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
if flags.isEmpty {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
}
이것은 3G 및 WiFi 연결 모두에서 작동합니다. 또한 작업 예제와 함께 GitHub에 업로드했습니다 .
답변
더 나은 방법을 제공합니다 …
이 코드로 클래스를 만들어야합니다.
import Foundation
public class Reachability {
class func isConnectedToNetwork()->Bool{
var Status:Bool = false
let url = NSURL(string: "http://google.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "HEAD"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0
var response: NSURLResponse?
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
Status = true
}
}
return Status
}
}
그런 다음이 코드를 사용하여 프로젝트의 어느 곳에서나 인터넷 연결을 확인할 수 있습니다.
if Reachability.isConnectedToNetwork() == true {
println("Internet connection OK")
} else {
println("Internet connection FAILED")
}
아주 쉽게!
*이 방법은 Vikram Pote 답변을 기반으로합니다!
답변
Swift 3.1 (iOS 10.1)의 경우
네트워크 유형 (예 : WiFi 또는 WWAN)을 구분하려면 :
당신이 사용할 수있는:
func checkWiFi() -> Bool {
let networkStatus = Reachability().connectionStatus()
switch networkStatus {
case .Unknown, .Offline:
return false
case .Online(.WWAN):
print("Connected via WWAN")
return true
case .Online(.WiFi):
print("Connected via WiFi")
return true
}
}
다음은 네트워크 유형을 구분하는 전체 도달 가능성 클래스입니다.
import Foundation
import SystemConfiguration
import UIKit
import SystemConfiguration.CaptiveNetwork
public let ReachabilityStatusChangedNotification = "ReachabilityStatusChangedNotification"
public enum ReachabilityType: CustomStringConvertible {
case WWAN
case WiFi
public var description: String {
switch self {
case .WWAN: return "WWAN"
case .WiFi: return "WiFi"
}
}
}
public enum ReachabilityStatus: CustomStringConvertible {
case Offline
case Online(ReachabilityType)
case Unknown
public var description: String {
switch self {
case .Offline: return "Offline"
case .Online(let type): return "Online (\(type))"
case .Unknown: return "Unknown"
}
}
}
public class Reachability {
func connectionStatus() -> ReachabilityStatus {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = (withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}) else {
return .Unknown
}
var flags : SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return .Unknown
}
return ReachabilityStatus(reachabilityFlags: flags)
}
func monitorReachabilityChanges() {
let host = "google.com"
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
let reachability = SCNetworkReachabilityCreateWithName(nil, host)!
SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in
let status = ReachabilityStatus(reachabilityFlags: flags)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: ReachabilityStatusChangedNotification), object: nil, userInfo: ["Status": status.description])}, &context)
SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue)
}
}
extension ReachabilityStatus {
public init(reachabilityFlags flags: SCNetworkReachabilityFlags) {
let connectionRequired = flags.contains(.connectionRequired)
let isReachable = flags.contains(.reachable)
let isWWAN = flags.contains(.isWWAN)
if !connectionRequired && isReachable {
if isWWAN {
self = .Online(.WWAN)
} else {
self = .Online(.WiFi)
}
} else {
self = .Offline
}
}
}
답변
sendSynchronousRequest가 더 이상 사용되지 않기 때문에 시도했지만 응답이 완료되기 전에 ‘return Status’가 호출되었습니다.
이 대답은 잘 작동합니다. Swift로 인터넷 연결을 확인하십시오.
어쨌든 내가 시도한 것은 다음과 같습니다.
import Foundation
public class Reachability {
class func isConnectedToNetwork()->Bool{
var Status:Bool = false
let url = NSURL(string: "http://google.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "HEAD"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
print("data \(data)")
print("response \(response)")
print("error \(error)")
if let httpResponse = response as? NSHTTPURLResponse {
print("httpResponse.statusCode \(httpResponse.statusCode)")
if httpResponse.statusCode == 200 {
Status = true
}
}
}).resume()
return Status
}
}
답변
SWIFT 3 :
에 대한 확인 와이파이 및 인터넷 연결 :
import Foundation
import SystemConfiguration
public class Reachability {
public func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
}
용법:
if Reachability.isConnectedToNetwork() == true {
print("Connected to the internet")
// Do something
} else {
print("No internet connection")
// Do something
}
답변
아래 답변을 사용할 수도 있습니다.
func checkInternet(flag:Bool, completionHandler:(internet:Bool) -> Void)
{
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let url = NSURL(string: "http://www.google.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "HEAD"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0
NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue(), completionHandler:
{(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
let rsp = response as NSHTTPURLResponse?
completionHandler(internet:rsp?.statusCode == 200)
})
}
func yourMethod()
{
self.checkInternet(false, completionHandler:
{(internet:Bool) -> Void in
if (internet)
{
// "Internet" mean Google
}
else
{
// No "Internet" no Google
}
})
}
답변
SWIFT 3 : 3G 및 Wi-Fi 연결 확인
DispatchQueue.main.async {
let url = URL(string: "https://www.google.com")!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) {data, response, error in
if error != nil {
// do something here...
print("Internet Connection not Available!")
}
else if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
// do something here...
print("Internet Connection OK")
}
print("statusCode: \(httpResponse.statusCode)")
}
}
task.resume()
}