Snap to Roads in Swift - swift

I am trying to implement a method that uses Googles snap to roads API however I have been unable to achieve any results.
I was able to successfully implement the directions API in to my Swift project using
https://maps.googleapis.com/maps/api/directions/json?origin=xyz
let request = NSURLRequest(URL: NSURL(string:directionURL)!)
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request,
completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) in
if error == nil {
let object = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSDictionary
println(object)
let routes = object["routes"] as! [NSDictionary]
for route in routes {
println(route["summary"])
}
dispatch_async(dispatch_get_main_queue()) {
//update your UI here
}
}
else {
println("Direction API error")
}
}).resume()
however if the GPS coordinates are even slightly different I get an entirely different result.
What I am trying to do is plot a users path the same each time even if the start/end coordinates a slightly different.
The error I am getting is
fatal error: unexpectedly found nil while unwrapping an Optional value
Any suggestions?
Thanks
EDIT:
I am trying this but this is what is causing the error
func directionAPITest() {
let directionURL = "https://roads.googleapis.com/v1/snapToRoads?path=-35.27801,149.12958|-35.28032,149.12907|-35.28099,149.12929|-35.28144,149.12984|-35.28194,149.13003|-35.28282,149.12956|-35.28302,149.12881|-35.28473,149.12836&interpolate=true&key=xyz"
let request = NSURLRequest(URL: NSURL(string:directionURL)!)
let session = NSURLSession.sharedSession()
}

I was able to resolve this after finding this post NSURL found nil while unwraping an Optional value
Basically had to escape the string.

Related

Can't get directions from GoogleMaps because of "found nil" unrapping URL

I searched through this topic and found some codes I tried to implement into my project, but it won't work!
So, what do I wanna achieve?
I wanna have a button in the UI, and when user tap the button, the app displays directions to a specific point on the GoogleMap. But my function crashes on the URL.
This is my code:
func draw(src: CLLocationCoordinate2D, dst: CLLocationCoordinate2D){
let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(src)&destination=\(dst)&sensor=false&mode=driving&key=**API_KEY**" <- // Here I place API-Key
let url = URL(string: urlString) // Here is the crash!
URLSession.shared.dataTask(with: url!, completionHandler: {
(data, response, error) in
if(error != nil){
print("error")
}else{
do{
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject]
let routes = json["routes"] as! NSArray
self.mapView.clear()
OperationQueue.main.addOperation({
for route in routes
{
let routeOverviewPolyline:NSDictionary = (route as! NSDictionary).value(forKey: "overview_polyline") as! NSDictionary
let points = routeOverviewPolyline.object(forKey: "points")
let path = GMSPath.init(fromEncodedPath: points! as! String)
let polyline = GMSPolyline.init(path: path)
polyline.strokeWidth = 3
let bounds = GMSCoordinateBounds(path: path!)
self.mapView!.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 30.0))
polyline.map = self.mapView
}
})
}catch let error as NSError{
print("error:\(error)")
}
}
}).resume()
}
I don't know if the problem could be with the API-key, or if there's something else. I read that spaces etc could cause this issue, but I can't find what's wrong!
Error message:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
2019-06-14 16:50:45 Fatal error: Unexpectedly found nil while unwrapping an Optional value
You wrongly create urlString with directly using CLLocationCoordinate2D as you have to use it's properties latitude/longitude
let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(src)&destination=\(dst)&sensor=false&mode=driving&key=**API_KEY**" <- // Here I place API-Key
it should be
let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(src.latitude),\(src.longitude)&destination=\(dst.latitude),\(dst.longitude)&sensor=false&mode=driving&key=**API_KEY**" <- // Here I place API-Key
Also it's better to avoid ! and do
guard let url = URL(string: urlString) else { return }

Error while obtaining URL/path of app using LSCopyApplicationURLsForBundleIdentifier and CFArrayGetValueAtIndex

I am using LSCopyApplicationURLsForBundleIdentifier to get the URL(s) of an installed third-party app on the target system based on its bundle identifier. However, when trying to retrieve the first URL from the returned CFArray, I keep getting the following error in the debugger at CFArrayGetValueAtIndex:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Here is the section of my Swift code:
let urls = LSCopyApplicationURLsForBundleIdentifier("com.aa.bb" as CFString, nil)
if (urls != nil) {
let url = unsafeBitCast(CFArrayGetValueAtIndex(urls as! CFArray, 0), to: CFString.self)
}
urls?.release()
url?.release()
How can I extract the URL correctly, preferably as String?
Too complicated, get the pointee with takeRetainedValue() – which handles the memory management properly – and cast it to [URL]
if let urls = LSCopyApplicationURLsForBundleIdentifier("com.aa.bb" as CFString, nil)?.takeRetainedValue() as? [URL],
let url = urls.first {
print(url)
}
An unsafeBitCast from (CF)URL to (CF)String is impossible anyway, to get a string path write
print(url.path)

do - try - catch code doesnt try or catch. just do's

thanks for any help upfront.
url session works perfect with connection, it prints the error as nil. but without it it prints the .localizedDescription just fine and shows me the right error, but then continues to do the do{ try } and crashes with this error in the try line:
Thread 6: Fatal error: Unexpectedly found nil while unwrapping an
Optional value
now I am not even sure if this has anything to do with the errorhandling. thanks for any help with understanding whats going on or just solving the problem!
func getData(completion: (() -> ())?) {
let urlString = URL(string: "https://api.coinmarketcap.com/v1/ticker/")
URLSession.shared.dataTask(with: urlString!, completionHandler: { (data, response , error) in
print("before entering do-try-catch", error?.localizedDescription)
do {
//create Dictionary
print("downloading content")
self.coinData = try JSONSerialization.jsonObject(with: data!) as! [[String:Any]]
//set connection status
self.connection = true
//update tableView
DispatchQueue.main.async {
completion?()
}
} catch {
print("catch", error.localizedDescription)
//set connection status
self.connection = false
//update tableView
DispatchQueue.main.async {
completion?()
}
}
}).resume()
}
Thread 6: Fatal error: Unexpectedly found nil while unwrapping an Optional value is a common problem for beginners.
You try to work with data that is not there.
So for example in your code you force to execute try JSONSerialization.jsonObject(with: data!)
When data is nil the code will crash.
The same at the beginning URLSession.shared.dataTask(with: urlString!, completionHandler: { (data, response, error) {}
When urlString is not a valid URL the code will be crash. (In this case the url seems to be valid).
For more information have a look here:
https://stackoverflow.com/a/24034551/4420355
Try the following snipped it should work
if let data = data {
self.coinData = try JSONSerialization.jsonObject(with: data) as? [[String:Any]]
//... work with coinData
}
Reason why it is crashing is because data is Optional and it should be nil or has some value. On line
self.coinData = try JSONSerialization.jsonObject(with: data!) as! [[String:Any]]
Compiler thinks:
Let's take a look and unwrap this Optianal variable. But it's nil, there is "nothing"! So what should I unwrap? Let's crash and throw Fatal Error message.
How to easily avoid this with Optional binding:
if let data = data {
....do something with data
} else {
...print error message
}
For more information take look at this brilliant answer.
https://stackoverflow.com/a/32170457/3046686

Xcode 7 Cast from XCUIElement to unrelated type 'String' always fails while fetching JSON

I am trying to fetch the values from JSON array and i am getting an error "Cast from 'XCUIElement!' to unrelated String always fails."
I am using Xcode 7 with iOS 9.1.
My code is as below:
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
print(error!.localizedDescription)
}
do {
let jsonResult = (try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSMutableArray
// print (jsonResult)
for usernames in jsonResult {
let influencer_username = usernames["influencer_username"] as! String
print("influencer_username: \(influencer_username)")
}
With Xcode 7.1.1 Not fixed but this workaround helped me:
let influencer_username = usernames["influencer_username"] as AnyObject as! String
I was able to solve this issue by removing the "themostplayedTests" from my Target Membership.

Swift Alamofire Unexpectedly found nil - Facebook API

I'm running the same exact function for Instagram and Youtube API with Alamofire and SwiftyJSON; however, with Facebook's API I get fatal error: unexpectedly found nil while unwrapping an Optional value.
var posts : [JSON] = []
func loadFBFeed() {
let url = "https://graph.facebook.com/mpstnews/posts/?access_token=\(apiKey)&date_format=U&fields=comments.limit(0).summary(1),likes.limit(0).summary(1),from,picture,message,story,name,link,created_time,full_picture&limit=5"
Alamofire.request(.GET, url).responseJSON { (request, response, json) -> Void in
switch json {
case .Success(let data):
let jsonObj = JSON(data)
if let postInfo = jsonObj["data"].arrayValue as [JSON]? {
self.posts = postInfo
self.tableView.reloadData()
}
case .Failure(_, let error):
print("Request failed with error: \(error)")
}
}
}
URL was using characters that Alamofire does not like, had to add a line to resolve...
var urlString = "https://graph.facebook.com/mpstnews/posts/?access_token=\(apiKey)&date_format=U&fields=comments.limit(0).summary(1),likes.limit(0).summary(1),from,picture,message,story,name,link,created_time,full_picture&limit=5"
urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
This generally happens when your URL is not valid. Most likely one of the values you are inserting into the URL is bad causing the URLStringConvertible logic to crash.