【问题标题】:NSURLConnection sendSynchronousRequest does not workNSURLConnection sendSynchronousRequest 不起作用
【发布时间】:2015-03-26 14:06:37
【问题描述】:

知道为什么sendSynchronousRequest 不起作用,并返回 nil。错误和响应也为零。

let url = NSURL(fileURLWithPath: "http://google.com")!
let ur = NSMutableURLRequest(URL: url)
let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil
let errorPtr = NSErrorPointer()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    let data = NSURLConnection.sendSynchronousRequest(ur, returningResponse: response, error: errorPtr)
    if errorPtr != nil {
        var error: NSError = errorPtr.memory!
    }
})

更新

我尝试了异步方式:

var oq = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(ur, queue: oq, completionHandler: {response, data, error in

    let ii = 7
})

这里出现错误:

(lldb) po 错误 错误域=NSURLErrorDomain 代码=-1100 “在此服务器上找不到请求的 URL。” UserInfo=0x1567f9d0 {NSErrorFailingURLStringKey=file:///http:/google.com, NSErrorFailingURLKey=file:///http:/google.com, NSLocalizedDescription=在此服务器上找不到请求的 URL。, NSUnderlyingError=0x15691880 "The在此服务器上未找到请求的 URL。"}

奇怪的google不可用?

【问题讨论】:

  • 既然可以轻松使用sendAsynchronousRequest:,为什么还要在dispatch_async中使用sendSynchronousRequest
  • 定义“不起作用”。没有println()调试调用,你有没有在sendSynchronousRequest调用后下断点检查结果?
  • 在编写代码并且它不起作用时,最好的方法是假设它是刚刚编写的代码,而不是系统。几十年来,这对我来说效果很好。仔细阅读错误消息通常会提供很好的信息,在这种情况下:“NSErrorFailingURLKey=file:///http:/google.com”是正确的。
  • 我也经常意识到我犯的错误不是系统:)
  • 在我的情况下,99% 以上的时间都是我的错误。 ;-)

标签: ios nsurlconnection


【解决方案1】:

您正在使用fileURLWithPath,这将返回 URL file:///private/var/folders/xs/6k9v2g217155wr9vgb3xrg_80000gn/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground-F81D60A5-6797-4BEB-8AB9 -2D156E2B6771/http://google.com

您需要的是let url = NSURL(string: "http://google.com")! ,它将返回 URL:
http://google.com

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多