class func checkUrl(urlString: String) -> Bool{ let urlPath: String = urlString var url: NSURL = NSURL(string: urlPath)! var request: NSURLRequest = NSURLRequest(url: url as URL) var response: URLResponse? let session = Foundation.URLSession.shared var task = session.dataTask(with: request as URLRequest,completionHandler: {(data,response,error) in if let error = error { print(error) } if let data = data{ print("data =\(data)") } if let response = response { print("url = \(response.url!)") print("response = \(response)") let httpResponse = response as! httpURLResponse print("response code = \(httpResponse.statusCode)") if httpResponse.statusCode == 200{ return true } else { return false } } }) task.resume()}
if else中的返回值返回错误:
为了返回值,你应该使用块.尝试声明你的功能如下:Unexpected non-voID return value in voID function
class func checkUrl(urlString: String,finished: ((isSuccess: Bool)->VoID) { let urlPath: String = urlString var url: NSURL = NSURL(string: urlPath)! var request: NSURLRequest = NSURLRequest(url: url as URL) var response: URLResponse? let session = Foundation.URLSession.shared var task = session.dataTask(with: request as URLRequest,error) in if let error = error { print(error) } if let data = data{ print("data =\(data)") } if let response = response { print("url = \(response.url!)") print("response = \(response)") let httpResponse = response as! httpURLResponse print("response code = \(httpResponse.statusCode)") if httpResponse.statusCode == 200{ finished(isSuccess: true) } else { finished(isSuccess: false) } } }) task.resume()}
然后像这样调用它:
checkUrl("http://myBestURL.com",finished { isSuccess in// Handle logic after return here})
希望这会有所帮助.
总结以上是内存溢出为你收集整理的swift – 使用dataTask返回值的函数全部内容,希望文章能够帮你解决swift – 使用dataTask返回值的函数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)