What is solution for "The file couldn’t be opened." UserInfo={NSURL=ftp:/xxxx:xxx#2011#ftp.xxx.com:21/}? - ios

I am trying to call FTP server api and want to get file name when api is success.
Below code I tried for call api,
let host = "ftp.xxx.com"
let user = "xxx"
let password = "xxx#2011"
let port = "21"
let url = URL(string: "ftp://"+user+":"+password+"#"+host+":"+port+"/")
var data: Data? = nil
do {
if let anUrl = url {
data = try Data(contentsOf: anUrl)
print(data!)
}
} catch {
print("Unexpected error: \(error).")
}
When run this code I am getting error like
Error Domain=NSCocoaErrorDomain Code=256 "The file couldn’t be opened." UserInfo={NSURL=ftp:/xxxx:xxx#2011#ftp.xxx.com:21/}.
Please give me any solution to solve this.

The problem is the plain # inside the password. This means ftp://xxxx:xxx#2011#ftp.xxx.com:21/ gets interpreted as connecting to server 2011#ftp.xxx.com with username xxxx and password xxx, which is obviously wrong.
The solution should be to URL-encode the special character # to %40, i.e. use the URL
ftp://xxx:xxx%402011#ftp.xxx.com:21/

Related

Error Domain=NSCocoaErrorDomain Code=257 "The file “Documents” couldn’t be opened because you don’t have permission to view it."

I have a problem accessing my files.
I am trying to create a file and send it over FTP. However, when I tried to read the file I created, I got this error message. Can you check where did I made a mistake?
The FTP upload was from https://gist.github.com/Nirma/fb9991be776107d17fdcd6ed2aa02876
The TXT file was created successfully with following codes, I can view it on my iPad simulator.
// Create TXTFile
let fileName = "test.txt"
self.save(text: "some text shown here", toDirectory: self.documentDirectory(), withFileName: fileName)
self.read(fromDocumentsWithFileName: fileName)
But the error happens when I execute the FTPupload codes.
// FTP upload
let ftp = FTPUpload(baseUrl: "XXX.XXX.XXX.XXX", userName: "XXXXXXX", password: "XXXXXXX", directoryPath: "XXXXX")
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
***let data = try Data(contentsOf: url as URL, options: [ .alwaysMapped, .uncached])***
ftp.send(data: data , with: "test.txt") { (success) in
print("success")
}
print(data)
}
catch {
print(error)
}
}
I have tracked down that the line with stars creates the error which shows I don't have the permission to view the file.
Can anyone help me? Thanks!

"The file “command.cgi” couldn’t be opened."

FlashAir W-04 Fourth Generation SD memory card
In my iOS app directory listing api not working.
Response :
Task .<0> HTTP load failed (error code: -1003 [12:8])
2019-05-21 23:32:40.267572+0530 Razzo[10489:87069] NSURLConnection finished with error - code -1003
Error Domain=NSCocoaErrorDomain Code=256 "The file “command.cgi” couldn’t be opened." UserInfo={NSURL=http://flashair/command.cgi?op=100&DIR=/DCIM}
Please help me what was wrong
below code snippet
private func getdata() {
let url100 = URL(string: "http://flashair/command.cgi?op=100&DIR=/DCIM")
var dirStr: String? = nil
do {
if let url100 = url100 {
dirStr = try String(contentsOf: url100, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
if let dir = dirStr {
arrayfiles = dir.components(separatedBy: "\n")
}
tblContent.reloadData()
}
} catch {
print(error)
self.displayAlert(message: error.localizedDescription)
}
}
Config file below
[Vendor]
CIPATH=/DCIM/100__TSB/FA000001.JPG
APPMODE=4
APPNETWORKKEY=12345678
VERSION=F15DBW3BW4.00.03
CID=02544d535733324755e3c6dc7b012301
PRODUCT=FlashAir
VENDOR=TOSHIBA
MASTERCODE=f437b71e0e4f
LOCK=1
contentsOf: url100 would be for a local file URL. You are not providing a valid file URL.
If your file is remote you need to download the file as data with URLSession. If it is local you need to work out its file URL.

Firebase Storage download to local file error

I'm trying to download the image f5bd8360.jpeg from my Firebase Storage.When I download this image to memory using dataWithMaxSize:completion, I'm able to download it.
My problem comes when I try to download the image to a local file using the writeToFile: instance method. I'm getting the following error:
Optional(Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown
error occurred, please check the server response."
UserInfo={object=images/f5bd8360.jpeg,
bucket=fir-test-3d9a6.appspot.com, NSLocalizedDescription=An unknown
error occurred, please check the server response.,
ResponseErrorDomain=NSCocoaErrorDomain, NSFilePath=/Documents/images,
NSUnderlyingError=0x1700562c0 {Error Domain=NSPOSIXErrorDomain Code=1
"Operation not permitted"}, ResponseErrorCode=513}"
Here is a snippet of my Swift code:
#IBAction func buttonClicked(_ sender: UIButton) {
// Get a reference to the storage service, using the default Firebase App
let storage = FIRStorage.storage()
// Get reference to the image on Firebase Storage
let imageRef = storage.reference(forURL: "gs://fir-test-3d9a6.appspot.com/images/f5bd8360.jpeg")
// Create local filesystem URL
let localURL: URL! = URL(string: "file:///Documents/images/f5bd8360.jpeg")
// Download to the local filesystem
let downloadTask = imageRef.write(toFile: localURL) { (URL, error) -> Void in
if (error != nil) {
print("Uh-oh, an error occurred!")
print(error)
} else {
print("Local file URL is returned")
}
}
}
I found another question with the same error I'm getting but it was never answered in full. I think the proposal is right. I don't have permissions to write in the file. However, I don't know how gain permissions. Any ideas?
The problem is that at the moment when you write this line:
let downloadTask = imageRef.write(toFile: localURL) { (URL, error) -> Void in
etc.
you don't yet have permission to write to that (localURL) location. To get the permission you need to write the following code before trying to write anything to localURL
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let localURL = documentsURL.appendingPathComponent("filename")
By doing it you will write the file into the following path on your device (if you are testing on the real device):
file:///var/mobile/Containers/Data/Application/XXXXXXXetc.etc./Documents/filename
If you are testing on the simulator, the path will obviously be somewhere on the computer.

Swift: downloadTaskWithURL sometimes "succeeds" with non-nil location even though file does not exist

The downloadTaskWithURL function sometimes returns a non-nil location for a file that does not exist.
There is no file at http://192.168.0.102:3000/p/1461224691.mp4 in the test environment.
Most of the time, invoking downloadTaskWithURL on this URL results in the expected error message:
Error downloading message during network operation. Download URL:
http://192.168.0.102:3000/p/1461224691.mp4. Location: nil. Error:
Optional(Error Domain=NSURLErrorDomain Code=-1100 "The requested URL
was not found on this server." UserInfo=0x17547b640
{NSErrorFailingURLKey=http://192.168.0.102:3000/p/1461224691.mp4,
NSLocalizedDescription=The requested URL was not found on this
server.,
NSErrorFailingURLStringKey=http://192.168.0.102:3000/p/1461224691.mp4})
Occasionally, and in a non-deterministic way, downloadTaskWithURL believes the file exists and writes something to the location variable. As a result, the guard condition does not fail, and the code continues to execute ... which it should not.
The permanent file created by fileManager.moveItemAtURL(location!, toURL: fileURL) is only 1 byte, confirming that the network file never existed in the first place.
Why does downloadTaskWithURL behave like this?
func download() {
// Verify <networkURL>
guard let downloadURL = NSURL(string: networkURL) where !networkURL.isEmpty else {
print("Error downloading message: invalid download URL. URL: \(networkURL)")
return
}
// Generate filename for storing locally
let suffix = (networkURL as NSString).pathExtension
let localFilename = getUniqueFilename("." + suffix)
// Create download request
let task = NSURLSession.sharedSession().downloadTaskWithURL(downloadURL) { location, response, error in
guard location != nil && error == nil else {
print("Error downloading message during network operation. Download URL: \(downloadURL). Location: \(location). Error: \(error)")
return
}
// If here, no errors so save message to permanent location
let fileManager = NSFileManager.defaultManager()
do {
let documents = try fileManager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let fileURL = documents.URLByAppendingPathComponent(localFilename)
try fileManager.moveItemAtURL(location!, toURL: fileURL)
self.doFileDownloaded(fileURL, localFilename: localFilename)
print("Downloaded file # \(localFilename). Download URL: \(downloadURL)")
} catch {
print("Error downloading message during save operation. Network URL: \(self.networkURL). Filename: \(localFilename). Error: \(error)")
}
}
// Start download
print("Starting download # \(downloadURL)")
task.resume()
}
Just to clarify, the server is returning a 404, but the download task is returning a basically-empty file? And you're certain that the server actually returned an error code (by verifying the server logs)?
Either way, I would suggest checking the status code in the response object. If it isn't a 200, then the download task probably just downloaded the response body of an error page. Or, if the status code is 0, the connection timed out. Either way, treat it as a failure.
You might also try forcing this to all happen on a single thread and see if the nondeterminism goes away.

plist attachment from email in swift (NS Cocoa Error Domain Code 260)

I am sending some ios file data via an email contained in a plist. No issues attaching it, I can check the file and the contents. It's all there and I can open it as a plist. Clicking on it (I have associated it with my app) it opens and I get a valid path:
file:///private/var/mobile/Containers/Data/Application/C5454580-2BEB-4515-9BDE-FED85FF54F76/Documents/Inbox/ShareStrength-11.bps
that I pass but when I try and read back the NSDictionary (plist) I get nil content.
let sourceFile = NSDictionary(contentsOfFile: URLString)
Any ideas on what is going wrong. Having difficulty debugging.
EDIT: I found some error code:
var error: NSError?
let content = NSString(contentsOfFile: URLString, encoding:NSUTF8StringEncoding, error: &error)
if content != nil
{
println("content: \(content)")
}
else
{
println("error: \(error)")
}
And I get the error:
error: Optional(Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x17eceeb0 {NSFilePath=file:///private/var/mobile/Containers/Data/Application/571DB0FF-6C5A-4BEB-9FA8-6E4DFE10E850/Documents/Inbox/ShareStrength-13.bps, NSUnderlyingError=0x17ee9810 "The operation couldn’t be completed. No such file or directory"})
Is this a sandbox issue? How can I copy the attachment being passed as a URL?
I was using:
let URLString: String = url.absoluteString!
instead of:
let URLString: String = url.path!
Hope this helps someone else

Resources