如何解决网络连接在swift中丢失错误?

时间:2015-02-06 06:29:09

标签: ios iphone swift nsurlconnection nsurlconnectiondelegate

我正在使用Xcode 6.1.1(6A2008a)。我创建了一个包含Download类的应用程序,这是Download类:

import Foundation
import UIKit
@objc protocol ConnectionDelegate
{
func ConnectionDidFinish(nstate: NSString, nData:NSData, strstatuscode:NSInteger)
func ConnectionDidFail(nstate: NSString, nData:NSString)
}
@objc class MyClass : NSObject,NSURLConnectionDelegate
{
var connDelegate:ConnectionDelegate?
var responseFromServer:NSHTTPURLResponse?
var dataWebService: NSMutableData = NSMutableData()
var activityView = UIActivityIndicatorView()
var strServiceName:NSString = ""

struct Static {
    static var instance:MyClass? = nil
    static var token:dispatch_once_t = 0
}
required override init() {

}

class func sharedConnectionWithDelegate(delegate:AnyObject)->MyClass
{

  Static.instance = self()
    Static.instance?.connDelegate=delegate as? ConnectionDelegate
    return Static.instance!

}

class func sharedConnection()->MyClass
{
   dispatch_once(&Static.token) {
        //          println("SQLiteDB - Dispatch once")
        Static.instance = self()
    }
    return Static.instance!

}
func GetStartUp(dic:NSDictionary,serviceName:NSString)
{
     self.strServiceName = serviceName
     self.getData(dic)

}
func getData(dataDict:NSDictionary)
{

   ShowNetworkActivityIndicator()
    if Reachability.isConnectedToNetwork()
    {
       let request3=NSMutableURLRequest(URL:NSURL(string: MainUrl)!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 100000.0)


    request3.HTTPMethod = "POST"
    var dict:NSDictionary? = dataDict
    if dict != nil
    {
        var error: NSError?
        var postData:NSData
        postData = NSJSONSerialization.dataWithJSONObject(dataDict, options:nil, error: &error)!
        var postDataLengthString:NSString = NSString(format:"%d", postData.length)
        request3.setValue(postDataLengthString, forHTTPHeaderField: "Content-Length")
        request3.HTTPBody=postData
    }
    request3.setValue("application/x-www-form-urlencoded charset=utf-8", forHTTPHeaderField: "Content-Type")
         var connection = NSURLConnection(request: request3, delegate: self, startImmediately: true)

    }
    else
    {
        HideNetworkActivityIndicator()
        connDelegate?.ConnectionDidFail("Internet connection is not available. Please try again later", nData: "Checking")
    }

}
//NSURLConnection delegate method
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!)
{
    println("get response")

    self.responseFromServer=response as? NSHTTPURLResponse
    dataWebService.length=0

    self.dataWebService = NSMutableData()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!)
{
    //Append incoming data
    println("get part of data")
    dataWebService.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!)
{
    println("get Full response data")
    HideNetworkActivityIndicator()
    var  statuscode:Int?=0
    statuscode = self.responseFromServer?.statusCode

    connDelegate?.ConnectionDidFinish(self.strServiceName, nData:self.dataWebService, strstatuscode:statuscode!)
}
func connection(connection: NSURLConnection!, didFailWithError getError: NSError!)
{
    HideNetworkActivityIndicator()
    var error:NSError?
    println("error during responsestring: %@, \(getError?.description)")
    var  statuscode:Int?=0
    statuscode = self.responseFromServer?.statusCode
    if statuscode == 1
    {
        println("Request Failed Status Code 1")
        connDelegate?.ConnectionDidFail("Internet connection is not available. Please try again later", nData: "Checking")
    }
    else
    {
        println("Request Failed Status Code unknown")
        var responseString:NSString! = NSString(data: self.dataWebService, encoding: NSUTF8StringEncoding)
            connDelegate?.ConnectionDidFail(getError.description, nData: responseString)
    }

}

我得到这种类型的错误NSURLConnection失败,错误域= NSURLErrorDomain Code = -1005“网络连接丢失。”在Swift iOS8中。

是否可以向我详细说明如何解决或解决此问题?

0 个答案:

没有答案