NSURLSession验证

时间:2016-01-07 15:50:24

标签: swift nsurlsession

我正在尝试使用Swift 2来处理正确(或至少是好)的方式来处理数据请求。

我想要达到的目的是:

  1. 检查数据连接是否可用,如果没有则提醒用户
  2. 如果连接可用,请提出请求
  3. 检查请求响应,如果无效,则提醒用户
  4. 如果有效,请检查响应代码并显示2条消息之一
  5. 到目前为止我有什么

        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")
                    }
    
                }
            }
        }
    

    目前如果我是在飞机模式下运行,那么没有任何反应,但我想抓住这个并告诉他们需要数据连接

1 个答案:

答案 0 :(得分:1)

试试这样:

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
}