我想要实现的是URLSession
在swift 3中执行请求.我在一个单独的函数中执行此操作(以便不为GET和POST单独编写代码)并返回URLSessionDataTask
并处理闭包中的成功和失败.有点像这样 -
let task = URLSession.shared.dataTask(with: request) { (data, uRLResponse, responseError) in
DispatchQueue.main.async {
var httpResponse = uRLResponse as! HTTPURLResponse
if responseError != nil && httpResponse.statusCode == 200{
successHandler(data!)
}else{
if(responseError == nil){
//Trying to achieve something like below 2 lines
//Following line throws an error soo its not possible
//var errorTemp = Error(domain:"", code:httpResponse.statusCode, userInfo:nil)
//failureHandler(errorTemp)
}else{
failureHandler(responseError!)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不希望处理此函数中的错误条件,并希望使用响应代码生成错误,并返回此错误以在任何调用此函数的位置处理它.任何人都可以告诉我该怎么做?或者这不是处理这种情况的"快速"方式吗?
我正在开发一个需要实时位置跟踪的应用程序,所以我正在使用startMonitoringSignificantLocationChanges
,即使应用程序已被用户从应用程序切换器强制退出,我的iOS 10模拟器上的一切正常.通过模拟器进行调试时,我正在使用高速公路驱动器选项,以便位置不断变化.
但是对于iOS 11模拟器: 当应用程序处于后台或前台模式时,服务器会根据用户的实时位置进行更新,但是当应用程序强行退出时,这不会发生.
服务器没有获得更新的位置,我甚至设置断点didFinishLaunching
并使用该wait for executable to be launched
设置来检查我是否得到回调,但我不适用于iOS 11而且适用于iOS 10.
我还使用iOS 11所需的适当值更新了info.plist,并确认我正在给予"始终"权限.我使用代码使用单例作为位置管理器对象:
func setupLocationManager(){
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.allowsBackgroundLocationUpdates = true
locationManager.requestAlwaysAuthorization()
locationManager.distanceFilter = 100.0
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.startMonitoringSignificantLocationChanges()
locationManager.startUpdatingLocation()
}
Run Code Online (Sandbox Code Playgroud)
并在应用程序委托:
if let _ = launchOptions?[UIApplicationLaunchOptionsKey.location] {
ChatSocketHelper.sharedInstance.socket.on("connect") { data, ack in
if let coordinate = LocationManager.shared.currentLocation?.coordinate{
ChatSocketHelper.sharedInstance.updateLocation([coordinate.longitude, coordinate.latitude])
}
}
}
Run Code Online (Sandbox Code Playgroud)
并在位置代表:
extension LocationManager : CLLocationManagerDelegate{
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { …
Run Code Online (Sandbox Code Playgroud)