NSURL fatal Error - swift

I try to make link to waze in Swift after i insert the url i get a fatal error.
My code:
let newName:String = closest.name.stringByReplacingOccurrencesOfString(" ", withString: "&", options: NSStringCompareOptions.LiteralSearch, range: nil)
print(closest.name)
print(newName)
let url:String = "waze://?q=\(newName)"
print(url)
let navAdd: NSURL? = NSURL(string:url)// here is the error
let wazeApp: NSURL? = NSURL(string: "http://itunes.apple.com/us/app/id323229106")!
print(navAdd)
if(true){
UIApplication.sharedApplication().openURL(navAdd!)
}else{
UIApplication.sharedApplication().openURL(wazeApp!)
}
and the error is:
fatal error: unexpectedly found nil while unwrapping an Optional value

You have unwrapped an optional with out checking if its not nil.
if let navAdd = NSURL(string:url) {
UIApplication.sharedApplication().openURL(navAdd)
} else if let wazeApp = NSURL(string:"http://itunes.apple.com/us/app/id323229106"){
UIApplication.sharedApplication().openURL(wazeApp)
} else {print("Url not found")}

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 }

how to check SwiftyJSON if returl nil in link

If my link does not return data how do I check in swiftyJSON,
I got this error : fatal error: unexpectedly found nil while unwrapping an Optional value
var URLString = mylink
URLString = URLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let url = NSURL(string: URLString)!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, innerError) in
let jsonData = NSData(contentsOfURL: url)! as NSData? //>> here is the error fatal error: unexpectedly found nil while unwrapping an Optional value
let readableJson = JSON(data: jsonData!, options: NSJSONReadingOptions.MutableContainers, error: nil)
let jjson = readableJson[0]
let ID = jjson["Title"]
})
}
task.resume()
You should avoid the force unwrap "!".
Try this
func foo(urlAsString:String) {
guard let
urlAsStringEscaped = urlAsString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding),
url = NSURL(string: urlAsStringEscaped)
else { fatalError() }
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
if let data = data where error == nil {
let json = JSON(data: data)
let id = json[0]["Title"].string
}
}
task.resume()
}

iOS - Swift - Parse - Twitter Profile Photo

1) I am trying to access twitter profile photo and upload it to the parse user object
2) Below is the code I am using.
if PFTwitterUtils.isLinkedWithUser(user){
//copy data to parse user
let screenName = PFTwitterUtils.twitter()?.screenName!
let requestString = ("https://api.twitter.com/1.1/users/show.json?screen_name=" + screenName!)
let verify: NSURL = NSURL(string: requestString)!
let request: NSMutableURLRequest = NSMutableURLRequest(URL: verify)
PFTwitterUtils.twitter()?.signRequest(request)
var response: NSURLResponse?
var error: NSError?
let data: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)!
if error == nil {
let result: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error)
//let names: String! = result?.objectForKey("name") as! String
//let separatedNames: [String] = names.componentsSeparatedByString(" ")
//var firstName = separatedNames.first!
//var lastName = separatedNames.last!
let urlString = result?.objectForKey("profile_image_url_https") as! String
let hiResUrlString = urlString.stringByReplacingOccurrencesOfString("_normal", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
let twitterPhotoUrl = NSURL(string: hiResUrlString)
let imageData = NSData(contentsOfURL: twitterPhotoUrl!)
if(imageData != nil) {
let profileFileObject = PFFile(data:imageData!)
user.setObject(profileFileObject, forKey: "profilePicture")
}
user.saveInBackgroundWithBlock({ (success:Bool, error:NSError?) -> Void in
if(success) {
//println("User details are now updated")
user.pinInBackgroundWithBlock({ (pinUserSuccess:Bool, pinUserError:NSError?) -> Void in
if (pinUserSuccess){
println("User successfully pinned in twitter")
}else {
println("Error in pining the user")
}
})
}
})
} else {
println(error?.description)
}
3) I am using Parse User Interface to sign in using twitter. That is working. I am able to access the screen name
4) I am testing this on a simulator
Question 1 -
In the above code I am getting an error for the below code. Please help!
let data: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)!
Error Domain=NSURLErrorDomain Code=-1012 \"The operation couldn’t be completed. (NSURLErrorDomain error -1012.)\" UserInfo=0x7fd11aab87a0 {NSErrorFailingURLStringKey=https://api.twitter.com/1.1/users/show.json?screen_name=jayskapadia, NSUnderlyingError=0x7fd11aab51b0 \"The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)\", NSErrorFailingURLKey=https://api.twitter.com/1.1/users/show.json?screen_name=jayskapadia}
Question 2 - I also want to access the email id from the twitter profile. How do I do that?
the photo part now works with the below code
if PFTwitterUtils.isLinkedWithUser(user){
//copy data to parse user.
let screenName = PFTwitterUtils.twitter()?.screenName!
let verify = NSURL(string: "https://api.twitter.com/1.1/account/verify_credentials.json")
var request = NSMutableURLRequest(URL: verify!)
PFTwitterUtils.twitter()!.signRequest(request)
var response: NSURLResponse?
var error: NSError?
var data:NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)!
if error == nil {
let result: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error)
//let names: String! = result?.objectForKey("name") as! String
//let separatedNames: [String] = names.componentsSeparatedByString(" ")
//var firstName = separatedNames.first!
//var lastName = separatedNames.last!
let urlString = result?.objectForKey("profile_image_url_https") as! String
let hiResUrlString = urlString.stringByReplacingOccurrencesOfString("_normal", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
let twitterPhotoUrl = NSURL(string: hiResUrlString)
let imageData = NSData(contentsOfURL: twitterPhotoUrl!)
if (screenName != nil){
user.setObject(screenName!, forKey: "username")
}
if(imageData != nil) {
let profileFileObject = PFFile(data:imageData!)
user.setObject(profileFileObject, forKey: "profilePicture")
}
user.saveInBackgroundWithBlock({ (success:Bool, error:NSError?) -> Void in
if(success) {
//println("User details are now updated")
user.pinInBackgroundWithBlock({ (pinUserSuccess:Bool, pinUserError:NSError?) -> Void in
if (pinUserSuccess){
println("User successfully pinned in twitter")
}else {
println("Error in pining the user")
}
})
}
})
} else {
println(error?.description)
}
}

Creating json swift app thing: fatal error: found nil when unwrapping json

I'm working on a json retrieving project or whatever, and I'm getting a fatal error while unwrapping a json. I think that the issue is that url is nil and I'm trying to unwrap it, but I'm not sure.
func getXRPData(urlString: String){
let url = NSURL(string: urlString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
dispatch_async(dispatch_get_main_queue(), {
self.setLabels(data)
})
}
task.resume()
}
func setLabels(xrpDataL: NSData){
var jsonError: NSError?
var percent = "%"
var dollarSIGN = "$"
let json = NSJSONSerialization.JSONObjectWithData(xrpDataL, options: nil, error: &jsonError) as! NSDictionary
//supply of xrp
if let supply = json["supply"] as? String{
var numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
if let result = numberFormatter.numberFromString(supply){
var finalResult = numberFormatter.stringFromNumber(result)
totalXRP.text = finalResult
}
}
Instead of force unwrapping, you should unwrap the results of JSONObjectWithData with an optional binding (if let) and a conditional downcast (as?):
if let json = NSJSONSerialization.JSONObjectWithData(xrpDataL, options: nil, error: &jsonError) as? NSDictionary {
// Continue parsing
} else {
// Handle error
}

fatal error: unexpectedly found nil while unwrapping an Optional value (Swift)

I am always getting the fatal error: unexpectedly found nil while unwrapping an Optional value. but if i look the the fileURL variable it has some values. please let me know what i missed here:
Error:
Optional(http:/files.parsetfss.com/461a4eda-d153-4d46-bd85-28ddd355a94c/tfss-03d4eb57-51cb-424d-8c90-2d8a89429203-00255--How_To_Build_A_Loving_Family.mp3 -- file:///)
fatal error: unexpectedly found nil while unwrapping an Optional value
Code:
if let audioFile = object["audioFile"] as? PFFile {
var audioPath: String = audioFile.url!
var fileURL = NSURL(fileURLWithPath: audioPath as String)
println(fileURL)
audioPlayer = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
audioPlayer.volume = volumeSlider.value
audioPlayer.play()
}
This code is working fine with your URL:
let url = "http://files.parsetfss.com/461a4eda-d153-4d46-bd85-28ddd355a94c/tfss-03d4eb57-51cb-424d-8c90-2d8a89429203-00255--How_To_Build_A_Loving_Family.mp3"
let soundData = NSData(contentsOfURL: NSURL(string: url)!)
var error: NSError?
self.audioPlayer = AVAudioPlayer(data: soundData, error: &error)
if audioPlayer == nil
{
if let e = error
{
println(e.localizedDescription)
}
}
audioPlayer!.volume = 1.0
audioPlayer!.prepareToPlay()
audioPlayer!.play()
This way you can convert your audio to data which will take some time to play your audio.
Here is another way to play song live:
let url = audioFile.url!
let playerItem = AVPlayerItem( URL:NSURL( string:url ) )
player = AVPlayer(playerItem:playerItem)
player.rate = 1.0;
player.play()