我有以下Swift代码,我向网络服务器发送POST请求并接收值。我收到的错误是在第二行到最后一行说"使用未解析的标识符"
func download_request() -> String {
let url:NSURL = NSURL(string: "http://url.com/read.php")!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let paramString = "data=name"
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.downloadTaskWithRequest(request) {
(let location, let response, let error) in
guard let _:NSURL = location, let _:NSURLResponse = response where error == nil else {
print("Error")
return
}
let urlContents = try! NSString(contentsOfURL: location!, encoding: NSUTF8StringEncoding)
guard let _:NSString = urlContents else {
print("Error")
return
}
}
task.resume()
return urlContents
}
我该如何解决此错误?我认为这意味着我不能在let task = session.downloadTaskWithRequest(request){}之外使用urlContents但是我如何声明变量以便我可以在外面使用它?
答案 0 :(得分:2)
尝试在urlContents
块之外声明session.downloadTaskWithRequest(request) { }
。像这样:
func download_request() -> String? {
let url:NSURL = NSURL(string: "http://url.com/read.php")!
let session = NSURLSession.sharedSession()
var urlContents: NSString?
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let paramString = "data=name"
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.downloadTaskWithRequest(request) {
(let location, let response, let error) in
guard let _:NSURL = location, let _:NSURLResponse = response where error == nil else {
print("Error")
return
}
urlContents = try? NSString(contentsOfURL: location!, encoding: NSUTF8StringEncoding)
guard let _:NSString = urlContents else {
print("Error")
return
}
}
task.resume()
return (urlContents as! String)
}
然后当你需要使用urlContents
用if let binding
if let contents = download_request() {
//Use safely unwrapped contents
}
答案 1 :(得分:0)
您可以按下面的方式返回optional
func download_request() -> String? {
var urlContents: String?
....
....
let task = session.downloadTaskWithRequest(request) {
(let location, let response, let error) in
...
...
...
guard let _:NSURL = location, let _:NSURLResponse = response where error == nil else {
print("Error")
return
}
urlContents = try! NSString(contentsOfURL: location!, encoding: NSUTF8StringEncoding) as String
guard let _:NSString = urlContents else {
print("Error")
return
}
}
task.resume()
return urlContents
}
并调用类似
的方法 if let request = download_request() {
//do anything with your request
}
建议您正确重命名方法,因为您返回的是下载的数据而不是请求。
这不是将下载的数据作为返回方法返回的正确方法,因为操作完成后将调用completionHandler
,因此urlContents
将为零。因此,创建另一种方法,将String
作为输入并在completionHandler
downloadTaskWithRequest
内调用它