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.
Related
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()
}
}
In my iOS app I'm trying to use the Facebook Swift SDK so that a user can post a URL to a specific Facebook page that they manage.
I've managed to get the following code working - but it only shares the post to my home timeline:
let content = LinkShareContent(url: URL(string: urlString)!)
let sharer = GraphSharer(content: content)
sharer.failsOnInvalidData = true
sharer.completion = {
(result) in
print(result)
}
do {
try sharer.share()
}
catch (let error) {
print(error.localizedDescription)
}
I believe that I need to use the graphNode property to specify the destination page and that the correct format is as follows:
sharer.graphNode = "/\(pageId)"
However, when I set this property before posting, I am getting an error:
failed(Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
I've tried a dozen different formats to specify the node but they all return the same error and I can't find any working examples.
I managed to resolved this issue. It turns out that the graphNode path above is correct but I was looking in the wrong place due to the error message I was getting. Instead I just needed to specify the accessToken parameter.
graphSharer.accesstoken = myPageAccessToken
Note: The access token is not the user's current access token, but an access token you can retrieve when calling the /me/accounts API.
var graphPath = "/me/accounts"
I also then had an issue posting to the page because I had only requested the publish_actions permission. From the documentation, this appears to be suitable but it only worked where I requested further permissions as follows:
loginManager.logIn(withPublishPermissions: ["publish_actions",
"manage_pages", "publish_pages"], ...
Hopefully this will be of use to someone in future. :-)
Quick background, I am extremely new in this realm. I am aware that this type of question has been asked before and answered successfully. The issue that I am experiencing is caused by the inability to wrap my head around the process of establishing the connection. I have spent hours (into days) searching for the answer and I am still unsuccessful. This has become my "white whale" so to speak.
I am using Xcode 9 with Swift version 4. Many of the answer I come across use Objective-C and I cannot mix and match. So I would like to UNDERSTAND why I am unable to connect and the correct process to connect so I can write the code with the understanding of what I am doing. Lastly, I have signed up (and completed) a few paid Udemy courses to try and learn the process correctly. I have been able to connect to API sources but OAuth 1 is tripping me up. Any constructive help would be incredibly appreciated.
Background:
I am attempting to connect to the Fat Secret database. I would like to connect a search bar to the food.search functionality and also the food.get for another search bar.
Company- FatSecret
URL for API- platform.fatsecret.com/rest/server.api
URL to FatSecret documentation (I have gone through this MANY times)- http:// {space} platform.fatsecret. {space }com/api/Default. {space} aspx?screen=rapiauth
Parameters- Parameters {
oauth_consumer_key - consumer_key (I have a consumer key)
oauth_signature_method - "HMAC-SHA1"
oauth_timestamp - The date and time, expressed in the number of seconds since January 1, 1970 00:00:00 GMT. The timestamp value must be a positive integer and must be equal or greater than the timestamp used in previous requests
oauth_nonce - A randomly generated string for a request that can be combined with the timestamp to produce a unique value
oauth_version - Must be "1.0"
}
As I previously stated, the answer to my question is displayed above. I understand that part but I do not understand how to incorporate it into my code.
Past code-
let url = URL(string: "I am unable to post more than 2 links due to my rep so I put {space} in the above url to circumvent the error. I used the listed url from the parameters")!
let task = URLSession.shared.dataTask(with: url) {
(data, response, error) in
if error != nil { print("success")
} task.resume()
The above code is what I used to establish the connection. I receive "success" in the console so I expanded my parameters.
let url = URL(string: "I am unable to post more than 2 links due to my rep so I put {space} in the above url to circumvent the error. I used the listed url from the parameters")!
let task = URLSession.shared.dataTask(with: url) {
(data, response, error) in
if error != nil { print(error)
if let urlContent = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(jsonResult)
} catch {
} task.resume()
The above code produces nothing in the console. I believe (sorry for my ignorance) that the reason I am not getting a response is because I am not sending any authorization in the request, nor am I am sending in the correct encoding. I imagine that I can create the parameters by var/let statements and then call on those statements but I am not able to see the way to do that. I could likely also store all of my connection information in a different swift file or class and call on that when I need to access data. This base signature is required with every request. I have to imagine that best practice would be setting it up that way but again, I can't visualization the process. It becomes a trial and error process that results in incredible frustration.
Again, any help would be incredibly appreciated. I apologize for the length of this post. Thank you for taking the time to read this post.
This may be late but I have successfully managed to implement the FatSecret REST API and have created a small Xcode project that shows how I handled OAuth. The only calls that can be made are food.search and food.get. https://github.com/NicholasBellucci/FatSecretSwift
I am using http://wsdl2swift.com/ to create an iOS Swift JSON Client who is calling an asmx-WebService.
Everything works great, i can build the connection, receive the result JSON-String inside the response XML, and it is printed inside the libraries "makeSoapConnection"-Function.
But if i call
let client = SyedAbsarClient()
let gam = GetAllBla()
gam.cpMyId = "12"
client.opGetAllBla(gam){(response: GetAllBlaResponse?, error:NSError?) -> Void in
print(response?.cpGetAllBlaResult)
}
i only get "nill"
As mentioned on the website, the utility is still under progress, For now, it returns the actual xml response that you can parse
print(response?.xmlResponseString)
I want to use the YouTube Data API to get the links to thumbnails for a specific YouTube video in my iOS app. I went to Google Developers Console and created a new project.
For that project I then went to "APIs" and removed the default APIs it enables for me and added the YouTube Data API. I then went to credentials, created a Public Key (as I don't need the user to log in or anything, just getting the thumbnail URLs) as iOS, which gave me an API key. I added the Bundle Identifier for my project under Allowed Applications.
Now in my app I tried the following code:
let test = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "https://www.googleapis.com/youtube/v3/videos?id=7lCDEYXw3mM&key=*MYKEYHERE*&part=snippet,contentDetails,statistics,status")!, completionHandler: { (data, response, error) -> Void in
let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
println("JSON: \(json)")
})
But it prints out the error:
JSON: Optional({
error = {
code = 403;
errors = (
{
domain = usageLimits;
message = "Access Not Configured. Please use Google Developers Console to activate the API for your project.";
reason = accessNotConfigured;
}
);
message = "Access Not Configured. Please use Google Developers Console to activate the API for your project.";
};
})
What exactly am I doing wrong?
There is a known problem about Bundle id in the console. If you can just remove that restriction, it should just work fine.
You can track the original issue from here: https://code.google.com/p/gdata-issues/issues/detail?id=5770
Here's what you need, YouTube has a service API via web to consult this types of things. I'm using this URL to consult all videos from a user (getting every videos: URL, Thumbnail, views, duration, etc). I'm sure you'll find thumbnails for a particular video. Its a JSON response so you'll have to take a good look to the structure but can't get simpler than this.
http://gdata.youtube.com/feeds/api/users/USER_NAME/uploads?v=2&alt=json&#&start-index=1&max-results=10