Firebase function not works on production, from IOS - ios

I do a call to Firebase function from ios/swift.
let functions = Functions.functions()
func callWrapper(funcName: String, data: Any? = nil) async -> [String: Any]? {
do {
let result = try await functions.httpsCallable(funcName).call(data)
return result.data as? [String : Any]
} catch {
if let error = error as NSError? {
if error.domain == FunctionsErrorDomain {
let code = FunctionsErrorCode(rawValue: error.code)
let message = error.localizedDescription
let details = error.userInfo[FunctionsErrorDetailsKey]
}
//todo handle
print(error)
}
return nil
}
}
I got next error.
2023-01-05 22:29:48.821609+0200 wallpapers[41492:641302] Task
<50374BAD-C312-450E-9770-B8300BE8FDB9>.<1> finished with error [-1007]
Error Domain=NSURLErrorDomain Code=-1007 "too many HTTP redirects"
UserInfo={NSLocalizedDescription=too many HTTP redirects,
NSErrorFailingURLStringKey=https://accounts.google.com/v3/signin/rejected?continue=https://uc.appengine.google.com/_ah/conflogin?state%3D~AJKiYcH_jc-hcv6OubZGrM13BmNN37rWX4x6rmTm7rZ4-Lqnr9Kk2C00oVNYR97TOiJ8lcR7vP91c9rv6o89HuwIlj85hxjrj63gbmu1jzGKzkU6S_kvHXv7yGdtaOWJnImTm02c6w9igKt3PbbWcawMsOafXEizRAd8jrT0jSe704DhXZ51m8IgAKv0kXxnblLuu3-DFmm-Uvi30sCPXIRGr_XG2DrMenI-zYGRjTiXf2uBVzIom7nVmKoCxIS7dGTvQozrDisq&dsh=S-1861899242:1672950586288679&flowEntry=ServiceLogin&flowName=WebLiteSignIn&ifkv=AeAAQh7QjO_naDvlYC2CVX-wduN9ft7CbGKMTlrMDHmAba7cHNPiDVDd4AQJzvAJgPnBpbS7sCeK0w&rhlk=no&rrk=32,
NSErrorFailingURLKey=https://accounts.google.com/v3/signin/rejected?continue=https://uc.appengine.google.com/_ah/conflogin?state%3D~AJKiYcH_jc-hcv6OubZGrM13BmNN37rWX4x6rmTm7rZ4-Lqnr9Kk2C00oVNYR97TOiJ8lcR7vP91c9rv6o89HuwIlj85hxjrj63gbmu1jzGKzkU6S_kvHXv7yGdtaOWJnImTm02c6w9igKt3PbbWcawMsOafXEizRAd8jrT0jSe704DhXZ51m8IgAKv0kXxnblLuu3-DFmm-Uvi30sCPXIRGr_XG2DrMenI-zYGRjTiXf2uBVzIom7nVmKoCxIS7dGTvQozrDisq&dsh=S-1861899242:1672950586288679&flowEntry=ServiceLogin&flowName=WebLiteSignIn&ifkv=AeAAQh7QjO_naDvlYC2CVX-wduN9ft7CbGKMTlrMDHmAba7cHNPiDVDd4AQJzvAJgPnBpbS7sCeK0w&rhlk=no&rrk=32,
_NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <50374BAD-C312-450E-9770-B8300BE8FDB9>.<1>" ), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <50374BAD-C312-450E-9770-B8300BE8FDB9>.<1>,
NSUnderlyingError=0x6000005f7c00 {Error Domain=kCFErrorDomainCFNetwork
Code=-1007 "(null)"}}.
If i run on local firebase simulator, it works fine
functions.useEmulator(withHost: "localhost", port: 5001)
i assume, i call function anonymously, and this might be a problem hovewer i want to do it as anonymous unauthorized user. Is it possible somehow to allow function to be called from unauthorized user? Or how to fix this problem? Thanks

Related

Facebook Graph API Issues

i am implementing facebook graph APi for get posts list but i am getting error in this Here Is my Code
var Requset : FBSDKGraphRequest
print("\(FBSDKAccessToken.current())")
let acessToken = String(format:"%#", FBSDKAccessToken.current().tokenString) as String
print("\(acessToken)")
let parameters1 = ["access_token":FBSDKAccessToken.current().tokenString]
Requset = FBSDKGraphRequest(graphPath:"me/?fields=feed{message,full_picture,id,application,likes{name,pic_crop},comments{message,from,created_time},created_time}", parameters:parameters1, httpMethod:"GET")
Requset.start(completionHandler: { (connection, result, error) -> Void in
//MBProgressHUD.hideHUDForView(appDelegate.window, animated: true)
if ((error) != nil)
{
print("Error: \(error)")
}
else
{
print("fetched user: \(result)")
//var dataDict: AnyObject = (result! as AnyObject).object(forKey: "data")!
}
i am getting error in this error is given below
Error: Optional(Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSUnderlyingError=0x60000005fbf0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}, NSErrorFailingURLStringKey=(null)?
can any one tell me how to solve this

Facebook SDK access token issue with Xcode 9.3

I have just updated phone iOS11.3 and Xcode 9.3, facebook login goes crash like this from my old SDK call:
https://pasteboard.co/HeeRDVo.png
I didn't understand what that mean exactly, even it works with older versions. Then I applied Swift SDK from that page, https://developers.facebook.com/docs/swift/graph.
import FacebookCore
let connection = GraphRequestConnection()
connection.add(GraphRequest(graphPath: "/me")) { httpResponse, result in
switch result {
case .success(let response):
print("Graph Request Succeeded: \(response)")
case .failed(let error):
print("Graph Request Failed: \(error)")
}
}
connection.start()
That gives below error log:
FBSDKLog: starting with Graph API v2.4, GET requests for //me should contain an explicit "fields" parameter
Graph Request Failed: Error Domain=com.facebook.sdk.core Code=8 "(null)" UserInfo={com.facebook.sdk:FBSDKGraphRequestErrorCategoryKey=0, com.facebook.sdk:FBSDKGraphRequestErrorHTTPStatusCodeKey=400, com.facebook.sdk:FBSDKErrorDeveloperMessageKey=An active access token must be used to query information about the current user., com.facebook.sdk:FBSDKGraphRequestErrorGraphErrorCode=2500, com.facebook.sdk:FBSDKGraphRequestErrorParsedJSONResponseKey={
body = {
error = {
code = 2500;
"fbtrace_id" = ____id____;
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
};
code = 400;
}}
It says, An active access token must be used to query information about the current user.
Even below code block gives same error when I made dictionaries comment line, because they don't work also.
import FacebookCore
struct MyProfileRequest: GraphRequestProtocol {
struct Response: GraphResponseProtocol {
init(rawResponse: Any?) {
// Decode JSON from rawResponse into other properties here.
}
}
var graphPath = "/me"
var parameters: [String : Any]? = ["fields": "id, name"]
var accessToken = AccessToken.current
var httpMethod: GraphRequestHTTPMethod = .GET
var apiVersion: GraphAPIVersion = .defaultVersion
}
let connection = GraphRequestConnection()
connection.add(MyProfileRequest()) { response, result in
switch result {
case .success(let response):
print("Custom Graph Request Succeeded: \(response)")
print("My facebook id is \(response.dictionaryValue?["id"])")
print("My name is \(response.dictionaryValue?["name"])")
case .failed(let error):
print("Custom Graph Request Failed: \(error)")
}
}
connection.start()
What should I do to overcome this issue?
Finally I have solved my problem using below method instead of annotation open url method in the AppDelegate. Hope that it helps others who encounter with this problem in iOS 11.3.
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(app,
open: url,
sourceApplication: options[.sourceApplication] as! String,
annotation: options[.annotation])
}

Alamofire Error.localizedDescription - The operation couldn’t be completed

I am trying to access the .localizedDescription property through Alamofire's callback in the event that there is an error
I have an enum which handles the Error types specifically similar to the Alamofire docs
enum BackendAPIErrorManager: Error {
case network(error: Error)
case apiProvidedError(reason: String) // this causes me problems
...
}
In my request, if there is an error I store the applicable error to the .failure case Alamofire provides as follows:
private func resultsFromResponse(response: DataResponse<Any>) -> Result<Object> {
guard response.result.error == nil else {
print(response.result.error!)
return .failure(BackendAPIErrorManager.network(error: response.result.error!))
}
if let jsonDictionary = response.result.value as? [String: Any], let errorMessage = jsonDictionary["error"] as? String, let errorDescription = jsonDictionary["error_description"] as? String {
print("\(errorMessage): \(errorDescription)")
return .failure(BackendAPIErrorManager.apiProvidedError(reason: errorDescription))
}
....
}
where that method is called in:
func performRequest(completionHandler: #escaping (Result<someObject>) -> Void) {
Alamofire.request("my.endpoint").responseJSON {
response in
let result = resultsFromResponse(response: response)
completionHandler(result)
}
}
Then when I call the performRequest(:) method, I check for the error in the completion handler:
performRequest { result in
guard result.error == nil else {
print("Error \(result.error!)") // This works
//prints apiProvidedError("Error message populated here that I want to log")
print(result.error!.localizedDescription) // This gives me the below error
}
}
In the event of an error where .failure(BackendAPIErrorManager.apiProvidedError(reason: errorDescription)) is returned, I receive the below error
The operation couldn’t be completed. (my_proj.BackendErrorManager error 1.)
How would I get the String value from the returned Error? I have tried .localizedDescription to no luck. Any help would be great!
To be able to call .localizedDescription on your custom BackendAPIErrorManager conforming to the Error protocol, you will need to add this code:
extension BackendAPIErrorManager: LocalizedError {
var errorDescription: String? {
switch self {
case .apiProvidedError:
return reason
}
}
}
The reason is a bit foggy (as the documentation on how the Error protocol works is not too detailed yet) but basically, in Swift 3, to be able to provide localized error descriptions (and other relative info), you need to conform to the new LocalizedError protocol.
You can find more details here:
How to provide a localized description with an Error type in Swift?

Swift Alamofire quit when request timed out

I wonder how I can exit out of my function when request timed out.
If I put my server offline and try to do some calls with this function the app will crash due to:
fatal error: unexpectedly found nil while unwrapping an Optional value
My Alamofire v3.x function looks like this:
static func loginWithFb(facebookId: String, email: String, username: String, response: (token: String?, errorVal: JSON?) -> ()) {
let urlString = baseURL + ResourcePath.FbLogin.description
let parameters: [String: AnyObject] = [
"facebook_id": facebookId,
"user_type": 1,
"email": email,
"username": username
]
Alamofire.request(.POST, urlString, parameters: parameters).responseJSON{ (responseData) -> Void in
let json = JSON(responseData.result.value!)
let token = json["api_key"].string
response(token: token, errorVal: json)
}
}
I get nil from:
let json = JSON(responseData.result.value!)
and the error:
FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7fc39349c4a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://mysite.dev/fb, NSErrorFailingURLKey=http://mysite.dev/fb,
_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}
fatal error: unexpectedly found nil while unwrapping an Optional value
So how can I exit the call if the request timed out? preventing it from trying to get the json data
Thanks,
You can increase the timeout interval if your service getting long time.
let request = NSMutableURLRequest(URL: NSURL.init(string: "your url")!)
request.HTTPMethod = "GET"
request.timeoutInterval = 250 // Set your timeout interval here.
Alamofire.request(request).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) { //Check for response
print(responseData.result.value!)
}
}
And must check that the response is not nil to resolve the issue of fatal error.
you need to know more about swift variable unwrapping, just a simple if(myJsonData != nil) would prevent the app crash, you can also add an alert box in case that there is no data on server or the server is down etc...
static func loginWithFb(facebookId: String, email: String, username: String, response: (token: String?, errorVal: JSON?) -> ()) {
let urlString = baseURL + ResourcePath.FbLogin.description
let parameters: [String: AnyObject] = [
"facebook_id": facebookId,
"user_type": 1,
"email": email,
"username": username
]
Alamofire.request(.POST, urlString, parameters: parameters).responseJSON{ (responseData) -> Void in
let myJsonData = JSON(responseData.result.value!)
if(myJsonData != nil)
{
let token = myJsonData["api_key"].string
}
else
{
// show alert box
}
}
}
Your issue is here
let json = JSON(responseData.result.value!)
you are force unwrapping value! instead you should wrap it in an if let
if let json = JSON(responseData.result.value) as? NSDictionary {
let token = json["api_key"].string
response(token: token, errorVal: json)
}
The timeout is fine and is not effecting your app in any way.

Swift: HTTP request executed correctly, but HTTPS not working

I try to execute GET request via HTTP by this code:
func httpGet(request: NSURL, callback: (String, String) -> Void) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(request) {
(data,response,error) -> Void in
if (error != nil) {
callback("", error!.localizedDescription)
} else {
let result = NSString(data: data!, encoding: NSASCIIStringEncoding)
callback(result! as String, "")
}
}
task.resume()
}
func updateIssueList () {
httpGet(NSURL(string: "http://www.google.com")!) {
(data, error) -> Void in
print("error: \(error)")
print("data: \(data)")
}
}
It's executed correctly, and returns data without error. But when I change protocol to HTTPS (https://www.google.com"), request fails. When I tried to run application on device (iPhone 4s), I recieved
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo=0x17579730 {NSErrorFailingURLStringKey=https://www.google.com, NSErrorFailingURLKey=https://www.google.com, NSLocalizedDescription=The network connection was lost., NSUnderlyingError=0x1758e470 "The network connection was lost."}
On simulator both variants work correctly. What I doing wrong?

Resources