Checking if song is present in user's Spotify library - ios

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=}

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.

Firebase method is returning an unknown Error

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}

The operation couldn’t be completed. (NSURLErrorDomain error -1011.)

I'm trying to upload an image to a FTP server using swift 4
I used FileProvider which is a library for Ftp connection iOS
anyway I'm checking the provider is reachable. and Im getting this error
The operation couldn’t be completed. (NSURLErrorDomain error -1011.)
this is the full error object:
Error Domain=NSURLErrorDomain Code=-1011 "(null)" UserInfo={NSErrorFailingURLKey=ftp://xxxx.xxxx.xxxx.xxxx:21/, NSErrorFailingURLStringKey=ftp://xxxx.xxxx.xxxx.xxxx:21/, NSURL=ftp://xxxx.xxxx.xxxx.xxxx:21/}
this is my code:
self.ftpProvider!.isReachable { (flag, error) in
if flag {
print("RIZK:--- provider is reachable ")
let progress = self.ftpProvider!.copyItem(localFile: localURL, to: "/files/\(imageName)", overwrite: true, completionHandler: { (error) in
if error == nil {
print("RIZK:-- Ready to upload")
}else{
print("RIZK:--\(error?.localizedDescription ?? "")")
}
})
print(progress?.fractionCompleted ?? 0)
}else{
print("RIZK:--- provider not reachable, with error \(error?.localizedDescription ?? "") ")
}
}

File rename failing with NSCocoaErrorDomain Code=513 on device

I'm trying to rename a file (a FileWrapper containing a UIDocument subclass) as follows:
coordinationQueue.async {
var error: NSError? = nil
let fileCoordinator = NSFileCoordinator(filePresenter: self)
fileCoordinator.coordinate(readingItemAt: url, options: .withoutChanges,
writingItemAt: targetURL, options: .forMoving, error: &error) { fromURL, toURL in
do {
fileCoordinator.item(at: fromURL, willMoveTo: toURL)
try FileManager().moveItem(at: fromURL, to: toURL)
fileCoordinator.item(at: fromURL, didMoveTo: toURL)
// Success!
} catch {
// Handle error
}
}
if let error = error {
// Handle error
}
}
… but it's failing on the moveItem, with the following error:
Error Domain=NSCocoaErrorDomain Code=513 "“from_file” couldn’t be moved because you don’t have permission to access “My_folder”." UserInfo={NSSourceFilePathErrorKey=/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/My_folder/from_file, NSUserStringVariant=(
Move
), NSDestinationFilePath=/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/My_folder/to_file, NSFilePath=/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/My_folder/from_file, NSUnderlyingError=0x1c1240ab0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
Interestingly, it works on fine on the simulator.
Can anybody help me out with this? (x-posted on Apple forums)

Data task with URL timed out

I am trying to access a website. I am using a dataTaskWithURL request.
Here is my code:
let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in
print("2")
if let urlContent = data {
print("3")
let stringContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)!
let arr = stringContent.componentsSeparatedByString("<b>The computer's solutions will appear below</b><br>")
let second = arr[1]
let newArr = second.componentsSeparatedByString("</tr></table></center><p align=\"center\">")
let results = newArr[0]
self.resultsLabel.text = results
self.stopActivity()
} else {
print(error)
self.stopActivity()
}
})
task.resume()
I have also tried running this code on the main block:
dispatch_async(dispatch_get_main_queue(), {() -> Void in
// Code
})
However, neither of these has been successful. I repeatedly get the following error
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7ff0a3f4c6e0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=THE URL I AM TRYING TO ACCESS, NSErrorFailingURLKey=THE URL I AM TRYING TO ACCESS, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.})
I have tried looking at this post and this one as well. However, I have not been successful with them. The website loads fairly quickly. How do I get rid of this error?
It could be caused by a number of things; If the issue is happening in the Simulator, I suggest restarting it as per the suggestions in the SO posts below:
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
Error: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."
NSURLErrorDomain Code=-1001 error when a http post request is sent
Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit
How to use NSURLSessionDataTask in Swift
It might be help to print response as well to see if the HTTP headers can provide a clue.
I realized that I was using https:// instead of http://.

Resources