iPhone에서 인터넷 연결을 확인하려고하면 많은 오류가 발생합니다. 누구 든지이 문제를 해결하도록 도울 수 있습니까?
코드:
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
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) ? true : false
}
}
코드 오류 :
읽을 수 없으면 오류 1은 다음과 같이 말합니다.
‘Int’는 ‘SCNetworkReachabilityFlags’로 변환 할 수 없습니다
오류 2 및 3 :
제공된 인수를 허용하는 ‘init’에 대한 과부하를 찾을 수 없습니다.
답변
의견에 언급 된 4G 문제를 해결하기 위해 @AshleyMills 도달 가능성 구현을 참조로 사용했으며 Swift 3.1의 Reachability를 다시 작성했습니다.
업데이트 : Xcode 10.1 • Swift 4 이상
Reachability.swift 파일
import Foundation
import SystemConfiguration
class Reachability {
var hostname: String?
var isRunning = false
var isReachableOnWWAN: Bool
var reachability: SCNetworkReachability?
var reachabilityFlags = SCNetworkReachabilityFlags()
let reachabilitySerialQueue = DispatchQueue(label: "ReachabilityQueue")
init(hostname: String) throws {
guard let reachability = SCNetworkReachabilityCreateWithName(nil, hostname) else {
throw Network.Error.failedToCreateWith(hostname)
}
self.reachability = reachability
self.hostname = hostname
isReachableOnWWAN = true
try start()
}
init() throws {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
throw Network.Error.failedToInitializeWith(zeroAddress)
}
self.reachability = reachability
isReachableOnWWAN = true
try start()
}
var status: Network.Status {
return !isConnectedToNetwork ? .unreachable :
isReachableViaWiFi ? .wifi :
isRunningOnDevice ? .wwan : .unreachable
}
var isRunningOnDevice: Bool = {
#if targetEnvironment(simulator)
return false
#else
return true
#endif
}()
deinit { stop() }
}
extension Reachability {
func start() throws {
guard let reachability = reachability, !isRunning else { return }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = Unmanaged<Reachability>.passUnretained(self).toOpaque()
guard SCNetworkReachabilitySetCallback(reachability, callout, &context) else { stop()
throw Network.Error.failedToSetCallout
}
guard SCNetworkReachabilitySetDispatchQueue(reachability, reachabilitySerialQueue) else { stop()
throw Network.Error.failedToSetDispatchQueue
}
reachabilitySerialQueue.async { self.flagsChanged() }
isRunning = true
}
func stop() {
defer { isRunning = false }
guard let reachability = reachability else { return }
SCNetworkReachabilitySetCallback(reachability, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachability, nil)
self.reachability = nil
}
var isConnectedToNetwork: Bool {
return isReachable &&
!isConnectionRequiredAndTransientConnection &&
!(isRunningOnDevice && isWWAN && !isReachableOnWWAN)
}
var isReachableViaWiFi: Bool {
return isReachable && isRunningOnDevice && !isWWAN
}
/// Flags that indicate the reachability of a network node name or address, including whether a connection is required, and whether some user intervention might be required when establishing a connection.
var flags: SCNetworkReachabilityFlags? {
guard let reachability = reachability else { return nil }
var flags = SCNetworkReachabilityFlags()
return withUnsafeMutablePointer(to: &flags) {
SCNetworkReachabilityGetFlags(reachability, UnsafeMutablePointer($0))
} ? flags : nil
}
/// compares the current flags with the previous flags and if changed posts a flagsChanged notification
func flagsChanged() {
guard let flags = flags, flags != reachabilityFlags else { return }
reachabilityFlags = flags
NotificationCenter.default.post(name: .flagsChanged, object: self)
}
/// The specified node name or address can be reached via a transient connection, such as PPP.
var transientConnection: Bool { return flags?.contains(.transientConnection) == true }
/// The specified node name or address can be reached using the current network configuration.
var isReachable: Bool { return flags?.contains(.reachable) == true }
/// The specified node name or address can be reached using the current network configuration, but a connection must first be established. If this flag is set, the kSCNetworkReachabilityFlagsConnectionOnTraffic flag, kSCNetworkReachabilityFlagsConnectionOnDemand flag, or kSCNetworkReachabilityFlagsIsWWAN flag is also typically set to indicate the type of connection required. If the user must manually make the connection, the kSCNetworkReachabilityFlagsInterventionRequired flag is also set.
var connectionRequired: Bool { return flags?.contains(.connectionRequired) == true }
/// The specified node name or address can be reached using the current network configuration, but a connection must first be established. Any traffic directed to the specified name or address will initiate the connection.
var connectionOnTraffic: Bool { return flags?.contains(.connectionOnTraffic) == true }
/// The specified node name or address can be reached using the current network configuration, but a connection must first be established.
var interventionRequired: Bool { return flags?.contains(.interventionRequired) == true }
/// The specified node name or address can be reached using the current network configuration, but a connection must first be established. The connection will be established "On Demand" by the CFSocketStream programming interface (see CFStream Socket Additions for information on this). Other functions will not establish the connection.
var connectionOnDemand: Bool { return flags?.contains(.connectionOnDemand) == true }
/// The specified node name or address is one that is associated with a network interface on the current system.
var isLocalAddress: Bool { return flags?.contains(.isLocalAddress) == true }
/// Network traffic to the specified node name or address will not go through a gateway, but is routed directly to one of the interfaces in the system.
var isDirect: Bool { return flags?.contains(.isDirect) == true }
/// The specified node name or address can be reached via a cellular connection, such as EDGE or GPRS.
var isWWAN: Bool { return flags?.contains(.isWWAN) == true }
/// The specified node name or address can be reached using the current network configuration, but a connection must first be established. If this flag is set
/// The specified node name or address can be reached via a transient connection, such as PPP.
var isConnectionRequiredAndTransientConnection: Bool {
return (flags?.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]) == true
}
}
func callout(reachability: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {
guard let info = info else { return }
DispatchQueue.main.async {
Unmanaged<Reachability>
.fromOpaque(info)
.takeUnretainedValue()
.flagsChanged()
}
}
extension Notification.Name {
static let flagsChanged = Notification.Name("FlagsChanged")
}
struct Network {
static var reachability: Reachability!
enum Status: String {
case unreachable, wifi, wwan
}
enum Error: Swift.Error {
case failedToSetCallout
case failedToSetDispatchQueue
case failedToCreateWith(String)
case failedToInitializeWith(sockaddr_in)
}
}
용법
AppDelegate.swift didFinishLaunchingWithOptions 메소드에서 초기화하고 발생할 수있는 오류를 처리하십시오 :
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
do {
try Network.reachability = Reachability(hostname: "www.google.com")
}
catch {
switch error as? Network.Error {
case let .failedToCreateWith(hostname)?:
print("Network error:\nFailed to create reachability object With host named:", hostname)
case let .failedToInitializeWith(address)?:
print("Network error:\nFailed to initialize reachability object With address:", address)
case .failedToSetCallout?:
print("Network error:\nFailed to set callout")
case .failedToSetDispatchQueue?:
print("Network error:\nFailed to set DispatchQueue")
case .none:
print(error)
}
}
return true
}
}
그리고 뷰 컨트롤러 샘플 :
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default
.addObserver(self,
selector: #selector(statusManager),
name: .flagsChanged,
object: nil)
updateUserInterface()
}
func updateUserInterface() {
switch Network.reachability.status {
case .unreachable:
view.backgroundColor = .red
case .wwan:
view.backgroundColor = .yellow
case .wifi:
view.backgroundColor = .green
}
print("Reachability Summary")
print("Status:", Network.reachability.status)
print("HostName:", Network.reachability.hostname ?? "nil")
print("Reachable:", Network.reachability.isReachable)
print("Wifi:", Network.reachability.isReachableViaWiFi)
}
@objc func statusManager(_ notification: Notification) {
updateUserInterface()
}
}
답변
Swift 3, Swift 4 (셀룰러 및 Wi-Fi 작업)의 경우 :
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(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
/* Only Working for WIFI
let isReachable = flags == .reachable
let needsConnection = flags == .connectionRequired
return isReachable && !needsConnection
*/
// Working for Cellular and WIFI
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let ret = (isReachable && !needsConnection)
return ret
}
}
용법:
if Reachability.isConnectedToNetwork(){
print("Internet Connection Available!")
}else{
print("Internet Connection not Available!")
}
답변
프로젝트 내에 새 Swift 파일을 작성하고 이름을 지정하십시오 Reachability.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(kCFAllocatorDefault, UnsafePointer($0))
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = flags == .Reachable
let needsConnection = flags == .ConnectionRequired
return isReachable && !needsConnection
}
}
이 코드를 사용하여 프로젝트의 어느 곳에서나 인터넷 연결을 확인할 수 있습니다.
if Reachability.isConnectedToNetwork() {
println("Internet connection OK")
} else {
println("Internet connection FAILED")
}
사용자가 인터넷에 연결되어 있지 않은 경우 사용자에게 알리는 경고 대화 상자를 표시 할 수 있습니다.
if Reachability.isConnectedToNetwork() {
println("Internet connection OK")
} else {
println("Internet connection FAILED")
var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
설명:
우리는 재사용 가능한 공개 수업과 인터넷 연결을 확인하기 위해 프로젝트의 어느 곳에서나 사용할 수있는 방법을 만들고 있습니다. Foundation 및 System Configuration 프레임 워크를 추가해야합니다.
공개 클래스 Reachability에서이 메서드 isConnectedToNetwork() -> Bool { }
는 인터넷 연결에 대한 부울 값을 반환합니다. 우리는 if 루프를 사용하여 필요한 조치를 수행합니다. 이것이 충분하기를 바랍니다. 건배!
답변
struct Connectivity {
static let sharedInstance = NetworkReachabilityManager()!
static var isConnectedToInternet:Bool {
return self.sharedInstance.isReachable
}
}
용법:
if Connectivity.isConnectedToInternet {
print("Connected")
} else {
print("No Internet")
}
답변
Cocoa Pods / Dependancy Manager없이 Ashley Mill의 Reachability 클래스 구현을 확인했습니다. 아이디어는 프로젝트에서 접근성 종속성을 자유롭게 만드는 것입니다.
Xcode 7.2-스위프트 2.1
1) https://github.com/ashleymills/Reachability.swift . Reachability 클래스를 프로젝트에 추가하십시오.
참고 : 추가하는 동안 ‘필요한 경우 항목 복사’가 선택되어 있는지 확인하십시오.
2) AppManager.swift 클래스를 만듭니다. 이 클래스는 공개 메소드 및 데이터가 추가되어 모든 VC에서 사용될 수있는 공개 모델 클래스로 제공됩니다.
// AppManager.swift
import UIKit
import Foundation
class AppManager: NSObject{
var delegate:AppManagerDelegate? = nil
private var _useClosures:Bool = false
private var reachability: Reachability?
private var _isReachability:Bool = false
private var _reachabiltyNetworkType :String?
var isReachability:Bool {
get {return _isReachability}
}
var reachabiltyNetworkType:String {
get {return _reachabiltyNetworkType! }
}
// Create a shared instance of AppManager
final class var sharedInstance : AppManager {
struct Static {
static var instance : AppManager?
}
if !(Static.instance != nil) {
Static.instance = AppManager()
}
return Static.instance!
}
// Reachability Methods
func initRechabilityMonitor() {
print("initialize rechability...")
do {
let reachability = try Reachability.reachabilityForInternetConnection()
self.reachability = reachability
} catch ReachabilityError.FailedToCreateWithAddress(let address) {
print("Unable to create\nReachability with address:\n\(address)")
return
} catch {}
if (_useClosures) {
reachability?.whenReachable = { reachability in
self.notifyReachability(reachability)
}
reachability?.whenUnreachable = { reachability in
self.notifyReachability(reachability)
}
} else {
self.notifyReachability(reachability!)
}
do {
try reachability?.startNotifier()
} catch {
print("unable to start notifier")
return
}
}
private func notifyReachability(reachability:Reachability) {
if reachability.isReachable() {
self._isReachability = true
//Determine Network Type
if reachability.isReachableViaWiFi() {
self._reachabiltyNetworkType = CONNECTION_NETWORK_TYPE.WIFI_NETWORK.rawValue
} else {
self._reachabiltyNetworkType = CONNECTION_NETWORK_TYPE.WWAN_NETWORK.rawValue
}
} else {
self._isReachability = false
self._reachabiltyNetworkType = CONNECTION_NETWORK_TYPE.OTHER.rawValue
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
}
func reachabilityChanged(note: NSNotification) {
let reachability = note.object as! Reachability
dispatch_async(dispatch_get_main_queue()) {
if (self._useClosures) {
self.reachability?.whenReachable = { reachability in
self.notifyReachability(reachability)
}
self.reachability?.whenUnreachable = { reachability in
self.notifyReachability(reachability)
}
} else {
self.notifyReachability(reachability)
}
self.delegate?.reachabilityStatusChangeHandler(reachability)
}
}
deinit {
reachability?.stopNotifier()
if (!_useClosures) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil)
}
}
}
3) 델리게이트 수업을 만듭니다. 대리인 방법을 사용하여 연결 상태를 알립니다.
// Protocols.swift
import Foundation
@objc protocol AppManagerDelegate:NSObjectProtocol {
func reachabilityStatusChangeHandler(reachability:Reachability)
}
4) UIViewController의 부모 클래스를 만듭니다 (상속 메소드). 부모 클래스에는 모든 자식 VC에 액세스 할 수있는 메서드가 있습니다.
// UIappViewController.swift
import UIKit
class UIappViewController: UIViewController,AppManagerDelegate {
var manager:AppManager = AppManager.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func reachabilityStatusChangeHandler(reachability: Reachability) {
if reachability.isReachable() {
print("isReachable")
} else {
print("notReachable")
}
}
}
5) AppDelegate에서 실시간 인터넷 연결 모니터링을 시작하십시오.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
AppManager.sharedInstance.initRechabilityMonitor()
return true
}
6) 상수 열거 형 값을 저장하기 위해 Swift File Name AppReference를 추가했습니다.
// AppReference.swift
import Foundation
enum CONNECTION_NETWORK_TYPE : String {
case WIFI_NETWORK = "Wifi"
case WWAN_NETWORK = "Cellular"
case OTHER = "Other"
}
7) ViewController에서 (예 : 네트워크를 사용할 수있는 경우에만 API를 호출하려고 함)
// ViewController.swift
import UIKit
class ViewController: UIappViewController {
var reachability:Reachability?
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
if(AppManager.sharedInstance.isReachability)
{
print("net available")
//call API from here.
} else {
dispatch_async(dispatch_get_main_queue()) {
print("net not available")
//Show Alert
}
}
//Determine Network Type
if(AppManager.sharedInstance.reachabiltyNetworkType == "Wifi")
{
print(".Wifi")
}
else if (AppManager.sharedInstance.reachabiltyNetworkType == "Cellular")
{
print(".Cellular")
}
else {
dispatch_async(dispatch_get_main_queue()) {
print("Network not reachable")
}
}
}
override func viewWillAppear(animated: Bool) {
}
override func didReceiveMemoryWarning() {
}
}
샘플은 https://github.com/alvinreuben/Reachability-Sample에서 다운로드 할 수 있습니다.
스위프트로 업그레이드 3.1-
https://github.com/alvinvgeorge/Reachability-UpgradedToSwift3
답변
Apple은 iOS12에서 네트워크 프레임 워크를 도입했습니다.
import Foundation
import Network
class NetworkReachability {
var pathMonitor: NWPathMonitor!
var path: NWPath?
lazy var pathUpdateHandler: ((NWPath) -> Void) = { path in
self.path = path
if path.status == NWPath.Status.satisfied {
print("Connected")
} else if path.status == NWPath.Status.unsatisfied {
print("unsatisfied")
} else if path.status == NWPath.Status.requiresConnection {
print("requiresConnection")
}
}
let backgroudQueue = DispatchQueue.global(qos: .background)
init() {
pathMonitor = NWPathMonitor()
pathMonitor.pathUpdateHandler = self.pathUpdateHandler
pathMonitor.start(queue: backgroudQueue)
}
func isNetworkAvailable() -> Bool {
if let path = self.path {
if path.status == NWPath.Status.satisfied {
return true
}
}
return false
}
}
답변
이것을 Swift-5 +에 사용하십시오
import Foundation
import UIKit
import SystemConfiguration
public class InternetConnectionManager {
private init() {
}
public static func isConnectedToNetwork() -> Bool {
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) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
}
용법:
InternetConnectionManager.isConnectedToNetwork{
print("Connected")
}else{
print("Not Connected")
}
아니면 그냥 framework
더 사용하십시오Utilities
: 링크