Using Simple Ping in swift (iOS)
Not sure why this doesn't work, but you can call the ping method yourself once the address is resolved.
A variable to tell you that you can start pinging:
var canStartPinging = false
The code that calls the ping:
let pinger = SimplePing(hostName: "www.apple.com")
pinger.delegate = self;
pinger.start()
do {
if (canStartPinging) {
pinger.sendPingWithData(nil)
}
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as! NSDate)
} while(pinger != nil)
The SimplePing
delegate method to wait for before you can start pinging:
func simplePing(pinger: SimplePing!, didStartWithAddress address: NSData!) {
println("didStartWithAddress")
canStartPinging = true
}
Ping a Website or an IP Address (or Check if a Website is Online) using Swift 4?
I guess the problem is easy: You enabled App Sandbox but didn't check Outgoing Connections.
What about your pingHost
method - it's completely correct. So I think only problem is in App Sandbox settings.
Pinging localhost in Swift w/ Xcode
If you print(error)
in your catch
block (which is always a good practice -- print("Failure!")
doesn't tell you why the catch
block was invoked) you'll notice that there's an error telling you:
The file couldn’t be opened because the specified URL type isn’t supported.
Although it isn't explicitly said, I think the implication here is that checkResourceIsReachable
is for filesystem URLs -- not remote http
requests.
Instead, use a system of verifying the URL is reachable meant for remote resources.
import SwiftUI
import Combine
class CheckURL : ObservableObject {
enum URLResult : String {
case unknown, unreachable, reachable
}
@Published var urlReachable : URLResult = .unknown
private var cancellable : AnyCancellable?
func verifyURL(urlPath: String) {
guard let url = URL(string: urlPath) else {
assertionFailure("Invalid URL")
self.urlReachable = .unknown
return
}
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
cancellable = URLSession.shared.dataTaskPublisher(for: url).tryMap({ (_ , response: URLResponse) -> URLResult in
if let response = response as? HTTPURLResponse, response.statusCode == 200 {
return .reachable
} else {
return .unreachable
}
})
.replaceError(with: .unreachable)
.receive(on: RunLoop.main).sink { result in
self.urlReachable = result
}
}
}
struct ContentView : View {
@StateObject private var urlChecker = CheckURL()
var body: some View {
Text("Reachable? \(urlChecker.urlReachable.rawValue)")
.onAppear {
urlChecker.verifyURL(urlPath: "http://localhost:4001/")
}
}
}
As mentioned in the comments, you'll want to make sure you have NSAllowsArbitraryLoads
set to YES
in your Info.plist
How to ping multiple hosts using SimplePing?
You need a fast enumeration loop.
Apple simple ping not work on iOS why?
Try adding this to your didStartWithAddress
:
- (void)simplePing:(SimplePing *)pinger didStartWithAddress:(NSData *)address
{
[pinger sendPingWithData:nil];
}
Swift: SimplePing timer not firing
With your chosen API you are responsible to schedule the timer on the runloop (what you didn't).
The self-scheduling API is
pingTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerFired), userInfo: nil, repeats: false)
Or use the more contemporary closure based API
pingTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { [weak self] timer in
self?.pingResponse = String(format: "Response = DID NOT RECIEVE LATENCY")
print(self?.pingResponse)
}
Related Topics
iOS 10.3 - How to Change App Icon Programmatically
Adding a Target to a Button Programmatically Throws an Error "Unrecognized Selector Sent to Class"
Didoutputsamplebuffer Delegate Not Called
Change Duration (Speed) on a Running Animation
How to Convert a Persian Date into a Gregorian in Swift
Avcapturevideopreviewlayer Add Overlays and Capture Photo in iOS
Drag Uibutton Without It Shifting to Center [Swift 3]
Firebase Connection Manager Should Return Only One Result
Longer Subtitles in Mapview Annotations (Swift)
iOS Swift App with More Photos: Performance and Storage Suggestions
Uitextfield Starting Cursor Position Is Wrong
Is There Really No Way to Style Sklabelnode
Uibezierpath + Cashapelayer - Animate a Circle Filling Up
Load Offline Cached JSON Using Afnetworking
Horizontal Paging Uicollectionview with Automatic Item Size in a Vertical Stack View
Countdown with Several Decimal Slots, Using Nstimer in Swift