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/