Silence "-canOpenURL: failed for URL:" - ios

I have added my URL schemes to Info.plist, as required by iOS 9. However, calls result in:
-canOpenURL: failed for URL: "scheme://" - error: "(null)"
being logged to the console. The calls are succeeding and returning the correct value, but these log messages are annoying. How can I disable them?

Try just using openURL: to check if it can open, since it returns a Bool, then call openURL: again:
if let url = NSURL(string: keyword) {
if UIApplication.sharedApplication().openURL(url) {
UIApplication.sharedApplication().openURL(url)
}
}
Looks weird to see the same statement repeated twice, but at least it doesn't spit out a failure message like canOpenURL: does. If anyone knows how to make it look less weird, please do tell.

Related

Swift 5.5: Async/Await URLSession.shared.data() throws an error

I tried to make use of the new Async/Await features in Swift 5.5 and tried the following code
let url = URL(string: "http://itunes.apple.com/lookup?bundleId=\(id)&country=at")
let (data, _) = try await URLSession.shared.data(from: url!)
let resultStruct = try jsonDecoder.decode(ResponseStruct.self, from: data)
Every time I execute this, the try await URLSession.shared.data(from: url!) part throws an error. If I catch it and print error.localizedString, I always get "cancelled". This happens with all different kinds of URLs. I tried to stick to the tutorials I found online, but what am I missing here?
EDIT: I forced the app into a runtime exception to get more details of the error:
Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSURLErrorDomain Code=-999 "cancelled"
As this post explains NSURLErrorDomain error code -999 in iOS, this error occurs when the SSL certificate of the server has issues, which I don't think is the case, as I am accessing the iTunes server or when the request gets canceled by anything else in my app, which looks like to be the case for me.
Change http to https. You cannot normally call insecure calls unless you add an exception to your Info.plist to disable App Transport Security.
There should be also a log from App Transport Security in your console.
Since ATS blocks the connection, the request gets cancelled.
See NSAppTransportSecurity for more info
I encountered the same problem in a SwiftUI app. I was using the task view modifier to load data asynchronously and update the view based on the loading states.
As mentioned in the documentation:
If the task doesn’t finish before SwiftUI removes the view or the view changes identity, SwiftUI cancels the task.
If this is your case, make sure to update the UI only after the task completes.
Alternative solution
Alternatively you can use the onAppear view modifier (which doesn't cancel the Task) and run the task inside its body:
Color.clear.onAppear {
Task {
await viewModel.load()
}
}

nw_read_request_report [C9] Receive failed with error "Software caused connection abort"

I got this error with application connection lost. While redirecting from another app to my app I face this issue.This issue triggered only on live app, getting error with connection lost and while debugging with Xcode getting error but redirected to specific view controller successfully I used deep linking with url scheme for handling response from another app. Still not getting clarity to what exact issue is there because not able to debug live app issue.
Working on iOS 13.2
In AppDelegate:
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
let components = NSURLComponents(url: url, resolvingAgainstBaseURL: true)
let params = components?.queryItems
signedResponse = (params?.first(where:{$0.name == "signedResponse"})?.value)!
self.decodedMsgString = String(data:Data(base64Encoded: signedResponse)!,encoding:.utf8)!
print("decodedMsgString : \(decodedMsgString)")
//Call API here
return true
}
I also ran into this issue, maybe this could give you an insight?
https://forums.developer.apple.com/thread/106838
From one of the replies
Following up, we determined that the issue was caused because our app continued to issue new NSURLConnection requests after going into the background and wasn't explicitly making them background tasks. As we didn't need background syncing, putting in code to prevent new requests from going out once the app was in the background eliminated this error.
There was the same problem, after returning to the application, it was necessary to make a short pause before requesting data from the deep link.
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
YourNetworkResponse
}

Firebase Cloud Functions Sending Error

I want to send an error to my iOS Application using Firebase Cloud Functions.
But I don't get any error when I use my url:
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
print(error) // Print nil
}
I have tried all these:
res.status(400).send("error");
res.status(400).send(New Error("error"));
console.error(new Error('A problem occurred'));
res.render({error:...})
Yea there is no way. The error message you send back like res.status(400).send("error"); is in the body itself. If you look at FIRFunctions.m file, it ignores that as it returns a firebase error message instead "Unimplemented" and "Internal" which are totally unconceptual and misleading messages. Like you get unimplemented error for res.status(400).send("error"). So the bottom line, the iOS SDK doesn't support it. You can to write your own localized error messages in your client side which is actually at the end better.

com.facebook.sdk.core error 8

This is more informative than anything. I couldn't for the life of me find anything on error code 8 when trying to access the login prompt (aka safari) when debugging my ios app. After I hit the log into facebook button in my app it would attempt to open safari then dump me back to the login page to my app. The error was being caused by the permissions array. I had the the permission "public_profile" spelled "public profile" which was throwing an error obviously. So make sure your permission are type corrected if you get the com.facebook.sdk.core error 8.
Hope that helps someone.
Make sure your permissions are typed correctly
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
if error == nil {
println("login complete")
self.performSegueWithIdentifier("showLogin", sender: self)
}else{
println(error.localizedDescription)
//com.facebook.sdk.core error 8.
}
}
In my case this error was caused by improper bundle id set in facebook settings of the app itself. Facebook "bundle id" is case sensitive, in my Info.plist I had uppercase product name, but in fb settings - lowercase.
In my case, I was using a Facebook account that hadn't yet been added to any of the Facebook app's admins/developers/testers roles.
In my case, after spending several hours of debugging I found that I was using the API,
func application(application: UIApplication,
openURL url: NSURL, options: [String: AnyObject]) -> Bool {
if #available(iOS 9.0, *) {
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: options)
} else {
// Fallback on earlier versions
}
return true
}
which is deprecated for iOS 9.So, I used:
func application(application: UIApplication,
openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
return true
}
Which worked for me. Hope this saves time of someone.
MAN!!! In my case it was the "bio" in the parameter that was causing this error. Facebook has changed the "bio" key to "about". So anyone using "bio" in parameters should change it to "about"
Pheww!!!
In my case It was wrong version. Instead of version: "v2.7", I used version: "2.7"
In my case it was because I listed name twice in the fields array. Assume that would apply to any field requested twice.
I had the same problem. It was because I didn't implement facebook login feature. After adding that, I logged in and my problem got solved.
In my case, I was playing with the Facebook Ads API and I tried to get a field but the name was wrong.
I had insights{date_start,date_end}, instead of insights{date_start, date_stop}.
More info here.
Hope it helps anyone.
In my case, I tried to get Facebook Id without logging into Facebook. Make sure you're logged into Facebook.
let accessToken = FBSDKAccessToken.current()
if accessToken != nil {
self.getCurrentUserFbId()
print("LoggedIn")
} else {
print("Not loggedIn")
self.loginIntoFacebook()
}
Hope this will helpful for anyone.
When it happened to me, I found that Facebook's access token was expired. Someone decided to store access token in UserDefaults and reuse it later. Of course all tokens more than ~2 months old were expired.
In my case it was because of GraphRequest.
The error response is
"com.facebook.sdk:FBSDKErrorDeveloperMessageKey" = "Syntax error
\"Expected end of string instead of \"%\".\" at character 5:
email%2Cname%2Cgender%2Cpicture";
"com.facebook.sdk:FBSDKGraphRequestErrorCategoryKey" = 0;
"com.facebook.sdk:FBSDKGraphRequestErrorGraphErrorCode" = 2500;
"com.facebook.sdk:FBSDKGraphRequestErrorHTTPStatusCodeKey" = 400;
"com.facebook.sdk:FBSDKGraphRequestErrorParsedJSONResponseKey" = {
body = {
error = {
code = 2500;
"fbtrace_id" = AFEUYbcYP39;
message = "Syntax error \"Expected end of string instead of \"%\".\" at character 5: email%2Cname%2Cgender%2Cpicture";
type = OAuthException;
};
};
code = 400;
};
The issue about that is https://github.com/facebook/facebook-swift-sdk/issues/309
In my case was because of birthday,friendlists . removing them started to work.
For me just had to go facebook developer under platform and activate deep linking
In our case we were seeing this issue while trying to log in with some test account (but not all). We were not following Facebook's recommended practice:
Before you test each use case below, make sure you remove your app from your test user's Facebook account using app settings.
After we did it for the failing test accounts, we were able to log in.

how to launch safari even when the url is not valid

I know how to launch safari using the:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://www.google.com"]];
But, this method returns false when the url is not valid, and nothing happens. So, I'd like to launch safari even when the url is invalid. Is it possible?
NO it is not possible to open URL (which is invalid) with safari or any other bowser in iOS or another OS, So it's better to make valid URL rather then fighting with it.
Using below code check, if the URL is valid or not.
NSURL *candidateURL = [NSURL URLWithString:candidate];
if (candidateURL && candidateURL.scheme && candidateURL.host)
{
//Open that URL using openURL method...
}
else
{
//Open any valid hardcoded URL using openURL method
}
Short answer? No.
Long answer? Technically No. But there is a workaround. If you use a redirection service/url shortener, you can hide your invalid url. For example, try this url: http://goo.gl/zRci0B
Safari will be able to open the link but it wont go anywhere. So what ever url(valid/invalid) you want to open, always wrap it with a redirection service.

Resources