2015-06-14 82 views
3

雨燕2.0更新之前,此代码后工作完全从一个PHP脚本的服务器下载我的JSON文件:NSURLConnection的抛出更新到雨燕2.0

let url = NSURL(string: webAdress) 
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData 
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 5.0) 

var response: NSURLResponse? = nil 
var error: NSError? = nil 
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error) 

后更新的Xcode要求我做一些改变。我做了,代码没有错误,但它总是抛出...

let url = NSURL(string: webAdress) 
    let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData 
    let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 5.0) 

    var response: NSURLResponse? = nil 
    var reply = NSData() 
    do { 
    reply = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response) 
    } catch { 
     print("ERROR") 
    } 

期待您的解决方案!

+3

打印出来的错误?你可以在捕获物内找到它。 – Rob

+0

print(error)会这样做 - 不需要声明一个错误变量(只是为你澄清Rob)。看到我的答案为Swifty的方式! – Sidetalker

回答

6

下面是使用新的NSURLSession一个例子 - 显然NSURLConnection的已弃用iOS中9

let url = NSURL(string: webAddress) 
let request = NSURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0) 

let session = NSURLSession.sharedSession() 

session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in 
    print(data) 
    print(response) 
    print(error) 
})?.resume() 

我认为这是超级干净,有它只是没有太多的文档。让我知道如果你有任何麻烦得到这个工作。

+0

感谢您的回复。这是我对你的代码的输出: '零 零 可选(错误域= NSURLErrorDomain代码= -1002 “URL nichtunterstützt” 的UserInfo = {0x1567d8b00 = NSUnderlyingError 0x1567a8c00“明镜Vorgang konnte nicht abgeschlossen werden(kCFErrorDomainCFNetwork-Fehler -1002 。“),NSErrorFailingURLStringKey = www.' _(...)_'.php,NSErrorFailingURLKey = www.' _(...)_'.php,NSLocalizedDescription = URL nichtunterstützt})' –

+0

你知道吗?可能? –

+0

数据和响应为零,因为您有错误。错误在那里被定义为可选的(就像数据和响应一样),所以如果你想使用任何信息,你必须打开它。你得到的错误1002对应于NSURLErrorUnsupportedURL,通常是由于缺少http://导致的。但是,这不是这种情况 - 我会看看这个错误。 – Sidetalker

1

马克西米利安喜, 我有同样的未解问题,通过使用Sidetalker是NSURLSession.dataTaskWithRequest不是你在寻找什么,因为NSURLSession API是高度异步建议的解决方案(与苹果的文档根据)和你的代码已经在实施swift 1.2是同步的。另一方面,另一方面,NSURLConnection在iOS 9中已被弃用,因此您编写的代码可能不会构建,对不对?

我建议的解决办法是:

let url = NSURL(string: webAdress) 
let request: NSURLRequest = NSURLRequest(URL: url!) 
let config = NSURLSessionConfiguration.defaultSessionConfiguration() 
let session = NSURLSession(configuration: config) 
var responseCode = -1 
let group = dispatch_group_create() 
dispatch_group_enter(group) 
session.dataTaskWithRequest(request, completionHandler: {(_, response, _) in 
if let httpResponse = response as? NSHTTPURLResponse { 
    responseCode = httpResponse.statusCode 
} 
dispatch_group_leave(group) 
})!.resume() 
dispatch_group_wait(group, DISPATCH_TIME_FOREVER) 
//rest of your code... 

请让我知道如果现在确定