NSURLConnection返回错误,但服务器显示请求状态200

时间:2015-02-05 21:20:42

标签: ios objective-c swift nsurlconnection nsurlrequest

我遇到了NSURLSession或NSURLConnection

的问题

我试图制作(例如)200个NSURLRequests。在发送请求时,我关闭手机连接(平面模式或关机wifi)并重新打开并关闭它......

有时,NSURLSession响应或NSURLConnection响应返回一个错误(NSData为nil,作为NSURLResponse)但是当我检查我的服务器时,我看到200状态的请求。如果我使用像Charles这样的代理,我也会看到请求。

似乎在发出请求时,如果连接丢失然后再次快速找到,即使返回错误,请求仍然完成

我怎样才能确定请求确实没有发送到服务器,因为连接丢失了?

以下是代码示例:

import UIKit

class ViewController: UIViewController {

lazy var queue: NSOperationQueue = NSOperationQueue()

override func viewDidLoad() {
    super.viewDidLoad()

    queue.name = "Queue"
    queue.maxConcurrentOperationCount = 1
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func sendRequests(sender: UIButton) {
    for(var i = 1; i<=200; i++) {
        let request = Request(page:i)
        queue.addOperation(request)
    }
}

}

我的NSOperation正在执行同步请求:

import Foundation
import UIKit

class Request: NSOperation {

var page: Int

init(page: Int) {
    self.page = page
}

override func main() {
    autoreleasepool {
        self.send()
    }
}

func send() {
    let url = NSURL(string: "http://localhost?p=\(page)")
    var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
    request.networkServiceType = NSURLRequestNetworkServiceType.NetworkServiceTypeBackground

    var response: NSURLResponse?
    var error: NSError?
    var data: NSData?

    data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)

    if(data == nil) {
        println("\(page) FAILED TO SEND")
    } else {
        println("\(page) SUCCESS")
    }

    if(error != nil) {
        println("\(page) ERROR : \(error?.debugDescription)")
    }

    if let httpResponse = response as? NSHTTPURLResponse {
        println("STATUS \(httpResponse.statusCode)")
    }
}   
}

任何帮助都将受到高度赞赏:)

由于

0 个答案:

没有答案