Reputation: 723
How to download a file over smb in Swift (tvOS)?
NetFS and Cooca are not available for tvOS and when I'm using URLSession dataTask smb://xxx.xxx.xxx.xx/share/test.txt
Swift tells me that smb is not a valid url.
Is there any solution to download a file over smb for tvOS?
Tried it with this code:
let url = self.smbManager.getFullUrl(fileName: self.file.name)
let request: NSURLRequest = NSURLRequest(url: url!)
let session = URLSession.shared
session.dataTask(with: request as URLRequest) { data, response, error in
print(data)
}.resume()
Error is:
finished with error [-1002] Error Domain=NSURLErrorDomain
Code=-1002
"unsupported URL"
UserInfo={NSLocalizedDescription=unsupported
URL,
NSErrorFailingURLStringKey=smb://xxx.xxx.xxx.xx/share/test.txt,
NSErrorFailingURLKey=smb://xxx.xxx.xxx.xx/share/test.txt,
_NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <B386A17C-A4A9-4C99-A70E-7E0C739712D3>.<1>"
),
_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask
<B386A17C-A4A9-4C99-A70E-7E0C739712D3>.<1>,
NSUnderlyingError=0x2813a7c60 {
Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"
}
}
Thanks.
Upvotes: 0
Views: 1194
Reputation: 569
Solution for smb:
let url = NSURL(string: "smb://xxx.xxx.xxx.xx/share/test.txt")
let request: NSURLRequest = NSURLRequest(URL: url!)
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request) { (data, response, error) -> Void in print("Response")
let reply = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(reply)
}
URLSession
is designed to make network transfers as easy as possible, and a great example of that is its `downloadTask() method. This fetches the contents of a URL you specify, saves it to a local file, then calls a completion handler so you can manipulate the file – all in one.
To demonstrate this, here’s some code to download the source code to the apple.com homepage:
let url = URL(string: "https://www.apple.com")!
let task = URLSession.shared.downloadTask(with: url) { localURL, urlResponse, error in
if let localURL = localURL {
if let string = try? String(contentsOf: localURL) {
print(string)
}
}
}
task.resume()
There are a few important things to note in there:
resume()
on it to make it happen.URLSession
on
your behalf.Upvotes: 0