Leo
Leo

Reputation: 224

NSURLSession validation

I'm trying o work out the correct (or at least a good) way to handle data request using Swift 2.

What i want to achieve is to:

  1. Check if a data connection is available, if no then alert the user
  2. If connection is available make a request
  3. Check request response, if invalid then alert the user
  4. if valid, check the response code and display one of 2 messages

what i have so far

    let requestURL: String = **********************
    let url = NSURL(string: requestURL)!
    let request = NSMutableURLRequest(URL: url)
    let session = NSURLSession.sharedSession()

    let postParams: NSDictionary = ["id":newId!]

    request.HTTPMethod = "POST"

    do {
        let jsonData = try NSJSONSerialization.dataWithJSONObject(postParams, options: [])
        let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
        let utf8str = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
        let base64Encoded = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
        let bodyData = "data="+base64Encoded!

        request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
    } catch {
        print("Error serialising JSON")
    }

    session.dataTaskWithRequest(request) { data, response, error in

        // Make sure response is OK
        guard let realResponse = response as? NSHTTPURLResponse where realResponse.statusCode == 200 else
        {
            // Show success message
            print("Invalid Response from server")
        }

        // Read JSON Data
        if let postString = NSString(data:data!, encoding: NSUTF8StringEncoding) as? String {
            if let responseData = postString.dataUsingEncoding(NSUTF8StringEncoding) {
                let json = JSON(data: responseData)
                let responseMessage:String = json["response"]["data"].stringValue
                if(responseMessage == "success")
                {
                   print("successful post")
                }else{
                   print("error saving post")
                }

            }
        }
    }

Currently if i was to run this in airplane mode then nothing happens, but i would like to catch this and tell these they need a data connection

Upvotes: 0

Views: 455

Answers (1)

Godlike
Godlike

Reputation: 1948

Try sth like this:

func connectedToNetwork() -> 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()
            if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
                return false
            }
            let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
            let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
            return (isReachable && !needsConnection)
            }

if(connectedToNetwork() == true){
//call your function to make the request
} else {
//show alert that they need an internet connection
}

Upvotes: 1

Related Questions