如何处理MKDirectionsRequest错误?递归调用Apple路由API崩溃求助
Hey there! Let's break down why your code is crashing on the 5th or 6th API call and get it sorted out.
First off, the direct cause of your crash is that force-unwrap (response?.routes)!—when the Apple Maps Directions API fails (which often happens after repeated calls due to rate limits, network blips, or no available routes), either response or response.routes will be nil. Force-unwrapping a nil optional guarantees a crash. On top of that, your outer do-catch block isn't helping here because directions.calculate doesn't throw errors—it passes failures to the completion handler's error parameter instead.
Here's how to fix this step by step:
1. Properly Handle Errors & Avoid Force-Unwrapping
Always check for errors first, then safely access the response and routes with optional binding instead of force-unwrapping. This prevents crashes and lets you handle edge cases gracefully:
directions.calculate(completionHandler: { (response, error) in // First, handle any API-level errors if let apiError = error { completion(nil, apiError) // Pass the error back to your completion handler return } // Safely retrieve routes without risking a crash guard let routes = response?.routes, !routes.isEmpty else { let noRoutesError = NSError(domain: "YourAppDomain", code: 1001, userInfo: [NSLocalizedDescriptionKey: "No valid routes found for this request"]) completion(nil, noRoutesError) return } // Now process each route safely for route in routes { // Your existing route processing code goes here } // Call completion with success once processing is done completion(result, nil) })
2. Respect Apple Maps API Rate Limits
This is almost certainly why you're hitting a crash after 5-6 calls—Apple's Directions API enforces rate limits to prevent abuse, and recursive calls can flood the API with requests in a short window. To fix this:
- Add a small delay (1-2 seconds) between recursive calls using
DispatchQueue.main.asyncAfterto space out requests. - Use a serial dispatch queue to ensure only one API call runs at a time, instead of firing all requests simultaneously.
- Check the error code returned by the API—if it's a rate limit error, implement exponential backoff (wait longer each time you hit the limit) before retrying.
3. Ensure Your Recursion Has a Clear Stop Condition
Double-check that your recursive logic has a definite termination point. If your code keeps calling the API indefinitely (even when it should stop), you'll hit rate limits faster and risk other unexpected crashes. For example, add a maximum call count to prevent infinite recursion.
By fixing the force-unwrapping, handling API errors properly, and respecting rate limits, your app should stop crashing and handle route calculations reliably.
内容的提问来源于stack exchange,提问作者Iona Ryder

