[Swift] インターネットに接続できるか確認する

以下のコードで確認できます。ちなみにSwiftのバージョンは2.0です。

Reachability.swift

import Foundation
import SystemConfiguration

public class Reachability {


    class func isConnectedToNetwork() -> Bool {

        var status:Bool = false

        let url = NSURL(string: "https://google.com")
        let request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod = "HEAD"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
        request.timeoutInterval = 10.0

        var response:NSURLResponse?

        do {
            let _ = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) as NSData?
        }
        catch let error as NSError {
            print("error happened")
            print(error.localizedDescription)
        }

        if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode == 200 {
                status = true
            }
        }
        return status
    }
}


使い方

let isOnline = Reachability.isConnectedToNetwork()

Related Contents

Pickup Contents