【发布时间】: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