Firebase method is returning an unknown Error - ios

I'm trying to send data to Cloud Storage using the Firebase SDK for iOS. In doing so I'm creating a reference (StorageReference) in this way:
let storageRef = Storage.storage().reference(forURL: Config.CONFIG_ROOF_REF).child("Posts").child(videoIDString)
And using the putFile method:
storageRef.putFile(from: videoURL, metadata: nil) { (metadata, error) in
if error != nil{
ProgressHUD.showError(error?.localizedDescription)
return
}
storageRef.downloadURL(completion: { (url, error) in
if error != nil {
return
}else {
self.videourl = url?.absoluteString
onSuccess(videourl!)
}
})
}
I pass in the argument videoURL and I receive back the error:
An unknown error occurred, please check the server response
I cannot understand why I receive that error since the videoURL I'm passing seems legit.
The videoURL I'm passing is this one:
file:///Users/andreagualandris/Library/Developer/CoreSimulator/Devices/7D3329AC-AD8D-4553-AC61-FDF8435134B6/data/Containers/Data/PluginKitPlugin/8229E521-A7A2-4C09-8312-CC6106C2FED8/tmp/trim.7CC60B3A-6982-4F42-AA63-ED094288A562.MOV
So I think this is a normal URL and there shouldn't be any problem with it.
The actual server response on the console is :
2020-01-26 10:31:27.107215+0100 InstagramClone[2517:235684] Task <4AC8F3F2-1CC6-4064-BBF7-6D0375769C9A>.<1> finished with error [-1] Error Domain=NSURLErrorDomain Code=-1 "unknown error" UserInfo={NSErrorFailingURLStringKey=https://firebasestorage.googleapis.com/v0/b/instagramclone-1ed36.appspot.com/o/Posts%2F412BA396-6CAD-4197-817F-1AA0D9E6E6FE?uploadType=resumable&name=Posts%2F412BA396-6CAD-4197-817F-1AA0D9E6E6FE&upload_id=AEnB2UoAHEWQ0WDv_Id2TK_xSL_71Jrj8kbmuDfLpGkO8fBe6e9sBF74QUj5r0MLdltJN79z5fWAtoqOx8JSAfpppyPe6qKrxA&upload_protocol=resumable, NSErrorFailingURLKey=https://firebasestorage.googleapis.com/v0/b/instagramclone-1ed36.appspot.com/o/Posts%2F412BA396-6CAD-4197-817F-1AA0D9E6E6FE?uploadType=resumable&name=Posts%2F412BA396-6CAD-4197-817F-1AA0D9E6E6FE&upload_id=AEnB2UoAHEWQ0WDv_Id2TK_xSL_71Jrj8kbmuDfLpGkO8fBe6e9sBF74QUj5r0MLdltJN79z5fWAtoqOx8JSAfpppyPe6qKrxA&upload_protocol=resumable, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"BackgroundUploadTask <4AC8F3F2-1CC6-4064-BBF7-6D0375769C9A>.<1>"
), _NSURLErrorFailingURLSessionTaskErrorKey=BackgroundUploadTask <4AC8F3F2-1CC6-4064-BBF7-6D0375769C9A>.<1>, NSLocalizedDescription=unknown error}

Related

The network connection is lost in swift

I am getting an error time to time while making requests,
Optional(Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <BB6171AF-E4AF-49F2-ACEE-A2CDA67B825E>.<3>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <BB6171AF-E4AF-49F2-ACEE-A2CDA67B825E>.<3>",
"LocalDataPDTask <BB6171AF-E4AF-49F2-ACEE-A2CDA67B825E>.<3>",
"LocalDataTask <BB6171AF-E4AF-49F2-ACEE-A2CDA67B825E>.<3>"
), NSLocalizedDescription=The network connection was lost., _kCFStreamErrorDomainKey=4, NSErrorFailingURLStringKey=https://url, NSErrorFailingURLKey=https://url})
Why am I getting this error?
I have a method which handles api calls called retry() and depending on the status i need to refresh my token and then retry the same request again. So what I have done is check whether the response after excuting the initial api call is SOMECODE and then refresh the access token if it is calling the refreshAccessToken method and depending on its response if it's a success then I recursively call the same function retry() again and excute the logic. It works fine sometimes and sometimes it gives the above error. The code which performs the above operation is posted below,
if responseDescDisplay == "SOMECODE"{
refreshAccessToken(){ isSuccess,isFailed, errCode in
if isSuccess {
retry(urlString: urlString, method: method, requestBody: requestBody, completionHandler: completionHandler)
performRetry = true;
}else{
if !performRetry {
if errCode.isEmpty {
completionHandler(nil,nil,"OHNO");
}else{
completionHandler(nil,nil,"ERROR");
}
}
}
My access token refreshing method looks something like this,
URLSession.shared.dataTask(with: tokenRegenerateRequest) { data, res, err in
print("EROR: ", err)
print("DARA: ", data)
if err != nil {
print("IN HERE")
completionHandler(false, false, "INTERNAL_SERVER_ERROR");
}
guard let data = data, err == nil else {return}
guard let httpResponse = res as? HTTPURLResponse else {
return
}
// print("REGENRATING TOKEN \(httpResponse.statusCode) \(res)");
if httpResponse.statusCode == 200 {
if !data.isEmpty {
do {
let decodedResponse = try! JSONDecoder().decode(RefreshTokenResponse.self, from: data);
print("ACCESS TOKEN REGENRATE REQUEST: ", decodedResponse)
if !decodedResponse.accessToken.isEmpty && !decodedResponse.refreshToken.isEmpty {
completionHandler(true,false, "")
} else {
print("HERE1")
completionHandler(false,true,"")
}
}catch{
print("HERE2")
completionHandler(false,true,"")
}
} else {
print("HERE3")
completionHandler(false,true,"")
}
}else {
print("HERE4", httpResponse.statusCode)
completionHandler(false,true,"")
}
}.resume()
What am i doing wrong. Why do I keep getting the above error? Please can anyone post/suggest a possible way to overcome this issue? Please don't suggest to use any other libraries since I am stick to URLSession. Thanks in advance.

Swift: Uploading a file to Firebase Storage from a Share Extension

I am trying to upload an image to firebase storage from a share extension in iOS, I have authed and am communicating with the database but when I attempt to upload the file it fails straight away.
I have made sure that the code that I am using works by using it in my main app. I have also made sure that the file is being saved in the file manager prior to being uploaded correctly.
Here is the code for saving the file prior to the upload:
if let data = downsizeImage(image: image).jpegData(compressionQuality: 0.2) {
let fileManager = FileManager.default
let url = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.<DOMAIN>.imageShare")?.appendingPathComponent("ImageToSend.jpg")
do {
try data.write(to: url!)
}
catch {
print(error.localizedDescription)
}
}
Here is the code for the upload task:
let storageRef: StorageReference = Storage.storage().reference().child(storageLocation).child(UUID().uuidString)
var completed = false
var mediaUploadTask: StorageUploadTask?
let mediaTimeoutTask = DispatchWorkItem{ () in
if !completed {
mediaUploadTask?.cancel()
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 30, execute: mediaTimeoutTask)
mediaUploadTask = storageRef.putFile(from: mediaUrl, metadata: nil) {(metadata, error) in
completed = true
...
}
What should happen is the image is successfully uploaded and the function would continue as normal. What actually happens is the upload fails nearly straight away. Here is the error returned:
Printing description of error:
▿ Optional<Error>
- some : Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown error occurred, please check the server response."
UserInfo={bucket=link-ages-55880.appspot.com,
_NSURLErrorFailingURLSessionTaskErrorKey=BackgroundUploadTask <AC5EADEA-6257-4C32-9454-17626156AA15>.<1>,
object=media/4qnjSBKysi79uCR3cTzf/04D22317-D2C0-4A5C-B032-4F37DB2C8F7A,
_NSURLErrorRelatedURLSessionTaskErrorKey=(
"BackgroundUploadTask <AC5EADEA-6257-4C32-9454-17626156AA15>.<1>"
),
NSLocalizedDescription=An unknown error occurred, please check the server response.,
ResponseErrorDomain=NSURLErrorDomain, ResponseErrorCode=-995}
If anyone has any idea what the problem might be, your ideas would be greatly appreciated. Thanks.
Here is a screenshot of the debugger:
I have found out what the problem was. Due to the way that iOS sandboxing works, calling:
storageRef.putFile(from: mediaUrl, metadata: nil, completion: {(metadata, error) in})
fails. More info Here: Original Answer.
Instead calling:
storageRef.putData(Data, metadata: nil, completion: {(metadata, error) in})
worked as intended.

Checking if song is present in user's Spotify library

Using the below code to check if the user's library contains a particular song. It returns an error. What could I be doing wrong? I couldn't find examples for this particular 'forCheckingIfSavedTracksContains' method anywhere.
let accessToken = SPTAuth.defaultInstance().sessionUserDefaultsKey
let request: URLRequest = try!
SPTYourMusic.createRequest(forCheckingIfSavedTracksContains: ["spotify:track:3ZakaL0QEt5eeD3N7HbaN1"], forUserWithAccessToken: accessToken)
SPTRequest.sharedHandler().perform(request) { (error, response, data) in
if error == nil {
print ("this is data\(String(describing: data))")
} else {
print ("error")
}
}
The error is:
Error Domain=NSURLErrorDomain Code=-1012 "(null)" UserInfo={NSErrorFailingURLStringKey=api.spotify.com/v1/me/tracks/contains?ids=, NSUnderlyingError=0x109e7eb60 {Error Domain=kCFErrorDomainCFNetwork Code=-1012 "(null)" UserInfo={_kCFURLErrorAuthFailedResponseKey=<CFURLResponse 0x109e7e970 [0x1b441e538]>{url = api.spotify.com/v1/me/tracks/contains?ids=}}}, NSErrorFailingURLKey=api.spotify.com/v1/me/tracks/contains?ids=}

Error when downloading from Firebase storage

I am trying to get basic upload/download working with the new Firebase storage. Uploading worked fine but I am unable to download the file to the device. Can someone please shed some light on what I am doing wrong. Thanks!
func downloadAudio() {
let storageRef = FIRStorage.storage().reference()
let pathReference = storageRef.child("testAudio/audio_test.m4a")
let localURL = getDocumentsDirectory().URLByAppendingPathComponent("audio_test2.m4a")
let downloadTask = pathReference.writeToFile(localURL) { (URL, error) -> Void in
if (error != nil) {
print("ERROR - ", error.debugDescription)
} else {
print("SUCCESS - ", URL)
}
}
}
PRINTS:
ERROR - Optional(Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown error occurred, please check the server response." UserInfo={ResponseErrorDomain=NSCocoaErrorDomain, object=testAudio/audio_test.m4a, NSURL=/Users/Ben/Library/Developer/CoreSimulator/Devices/02AF50F2-E9BE-4EED-A3BE-485D63264731/data/Containers/Data/Application/31BDED56-0135-4E70-943E-F897080768D6/Documents/, bucket=mydevslopesapp.appspot.com, ResponseErrorCode=518, NSLocalizedDescription=An unknown error occurred, please check the server response.})
This is not a storage error, it's actually an issue with the file you're attempting to write to.
Looks like URLByAppengingString should be fileURLWithPath to get a file system URL (per NSFileManager creating directory error 518 NSFileWriteUnsupportedSchemeError).
Long term we need to fish this out and serve it as a "see relevant error" rather than "read network response."

Parse JSON in SWIFT

Hi i try to find a way to parse JSON in SWIFT, this works great for me but i run into a problem.
I let the user enter a username that is used for the JSON URL -> if the user type in a valid username all works fine.
But if he enter a wrong username my parsing fails, this is correct too, but for now my app only crashes and i looking for a way to make a work around.
This is my Code where it crashes,
let url0 = NSURL(string: newUrlPath!)
let session0 = NSURLSession.sharedSession()
let task0 = session0.dataTaskWithURL(url0!, completionHandler: {data, response, error -> Void in
if (error != nil) {
println(error)
} else {
let summonorID_JSON = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
The Xcode Error
Error Domain=NSURLErrorDomain Code=-1002 "The operation couldn’t be
completed. (NSURLErrorDomain error -1002.)" UserInfo=0x7c12d610
{NSErrorFailingURLKey=XX, NSErrorFailingURLStringKey=XX,
NSUnderlyingError=0x7c12c8d0 "The operation couldn’t be completed.
(kCFErrorDomainCFNetwork error -1002.)"} fatal error: unexpectedly
found nil while unwrapping an Optional value
All is fine cause this is the return page i get from my Request
https://br.api.pvp.net/api/lol/br/v1.4/summoner/by-name/smirknaitiax?api_key=5c7d4d4f-f320-43d5-8647-643c9f6ee5de
And yes he can't parse this into a NSDirectory as its no JSON that returns (as its normally is) is there a way to take care that if this page comes up (so the user entered a wrong username) that i can exit my loop/take a other way ;)?
You are using many operations which could all fail, and Swift is quite unforgiving about failure. Your code will crash if newURLPath is nil, if url0 is nil because newURLPath wasn't a valid URL.
So your URL request might return an error (the request itself failed), but you have the case that the URL request succeeded but gives unexpected results (not a JSON dictionary). Your code ending in "as NSDictionary" tells Swift: "I know I might not get a dictionary, but convert what you get to a dictionary and crash if this doesn't work". Just change this to
if let parsedJSON = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)
{
// Will still crash if the server sends a valid JSON array
let summonorID_JSON = parsedJSON as NSDictionary
}
else
{
// data wasn't valid JSON, handle it.
}
The difference is that the optional value returned by the JSON parser will be accepted without crashing, and you check whether you received valid JSON or not.
Since you are getting 404 on this request, I assume that this will happen every time something is bad with username, you should handle server response to fit that. First thing will be to check what server returned:
let httpResp: NSHTTPURLResponse = response as NSHTTPURLRespons
At this point you can access statusCode property, that will tell you if request was good or not (404). Having that information you can decide what to do, and for example, you can modify your code something like this:
let url0 = NSURL(string: newUrlPath!)
let session0 = NSURLSession.sharedSession()
let task0 = session0.dataTaskWithURL(url0!, completionHandler: {data, response, error -> Void in
if (error != nil) {
println(error)
} else {
let httpResp: NSHTTPURLResponse = response as NSHTTPURLRespons
httpResp.statusCode != 404 {
let summonorID_JSON = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
} else {
// Handle error at this point, tell user to retype username etc.
}
})
NSURL is a failable initializer and exactly this happens when you give an invalid url: It fails to initialize.
So wrap your code in an conditional unwrap:
if let url0 = NSURL(string: newUrlPath!) {
...
}
The url0 becomes nil if user enter wrong data. If you use the nil value as url0! app will crash.
When you add a ! after a variable you tell the compiler the value will not be nil.
so to avoid the crash, you have to check for nil condition before calling
let task0 = session0.dataTaskWithURL(url0!, completionHandler: {data, response, error -> Void in

Resources