Reputation: 4299
I'm working on a simple project to help learn Swift and I'm running into a problem that I think has deeper implications / learning opportunities (trying to look on the bright side).
The high-level problem is that when I POST JSON-encoded parameters using AlamoFire, a EXC_BAD_ACCESS error quickly appears in a separate line of code where I set one of the parameters (specifically CoreLocation Manager's "didUpdateLocations") ... here's the code:
In ViewController, I create a mutable dictionary:
var parameters = [String:AnyObject]()
And, for the didUpdateLocations
event, I assign the updated latitude / longitude values to the respective keys in the mutable dictionary.
class ViewController: UIViewController, CLLocationManagerDelegate {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
...
func locationManager(locManager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
appDelegate.parameters["longitude"] = locManager.location.coordinate.longitude
appDelegate.parameters["latitude"] = locManager.location.coordinate.latitude
}
Finally, I have a periodic function (using NSTimer.scheduledTimerWithTimeInterval
) that POSTs to a server.
func updatePost() {
println("POSTing update")
Alamofire.request(.POST, "http://server.co/endpoint",
parameters: appDelegate.parameters, encoding: .JSON)
}
If I comment out the Alamofire POST, everything is fine. With the POST, I get the EXC_BAD_ACCESS error at the first line of the didUpdateLocations (where the longitude
key is set)
I suspect it's something to do with how the parameters are converted by the encoding routine of Alamofire, but I have no idea why it would appear up in the didUpdateLocations function and not in the Alamofire call itself ...
Can anyone provide any insights? Thank you
Upvotes: 0
Views: 776
Reputation: 93276
What's happening is that you have multiple threads trying to access a Dictionary
at the same time. When you modify parameters
in didUpdateLocations
, it likely moves in memory while it's being read inside Alamofire, causing the EXC_BAD_ACCESS exception.
To solve this I would stop updating the parameters
dictionary from within didUpdateLocations
- add a latestLocation
property to your view controller and update that instead. Then, inside updatePost
, create your dictionary of parameters and pass it to Alamofire.request
.
Upvotes: 2