SFTP using NSURLSession does not work

Please help connect to my server using SFTP, I tried a lot. But it does not work properly. The server is working fine.

// The first method

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let userPasswordString = "username : password"
        let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
        let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
        let authString = "Basic \(base64EncodedCredential)"
        config.HTTPAdditionalHeaders = ["Authorization" : authString]
        let session = NSURLSession(configuration: config)

        let url = NSURL(string: "sftp.myserver.com")
        let task = session.dataTaskWithURL(url!) {
            (let data, let response, let error) in
            // data - nil, response - nil
         }

        task.resume()

// Second method

  func connect()  {

        let url: NSURL = NSURL(string: "sftp.myserver.com")!
        let login:String = "username"
        let password:String = "password"

        let defaultCredentials: NSURLCredential = NSURLCredential(user: login, password: password, persistence: NSURLCredentialPersistence.ForSession)

        let host: String = "myserver.com"
        let port: Int = 22
        let prot: String = "sftp"


        let protectionSpace: NSURLProtectionSpace = NSURLProtectionSpace(host: host,port: port,`protocol`: prot,realm: nil,authenticationMethod: NSURLAuthenticationMethodServerTrust)

        let credentialStorage: NSURLCredentialStorage = NSURLCredentialStorage.sharedCredentialStorage()
        credentialStorage.setCredential(defaultCredentials, forProtectionSpace: protectionSpace)

        let sessionConfiguration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
        sessionConfiguration.URLCredentialStorage = credentialStorage

        let session: NSURLSession = NSURLSession(configuration: sessionConfiguration)

        let task = session.dataTaskWithURL(url, completionHandler: { data, response, _ -> Void in

            // data- nil, response - nil

            if let dataRRR = data, jsonResult = try! NSJSONSerialization.JSONObjectWithData(dataRRR, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {

                print(jsonResult)
             }
        })
        task.resume()
    }

// The third method

func heloo() {

        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: configuration)
        let login:String = "username"
        let password:String = "password"
        let params:[String: AnyObject] = [
            "email" : login,
            "userPwd" : password ]

        let url = NSURL(string:"sftp.myserver.com")
        let request = NSMutableURLRequest(URL: url!)
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.HTTPMethod = "POST"

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions(rawValue: 0))

        let task = session.dataTaskWithRequest(request) {
            data, response, error in

            // data - nil, response - nil

            if let dataRRR = data, jsonResult = try! NSJSONSerialization.JSONObjectWithData(dataRRR, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {

                print(jsonResult)
            }

        }
        task.resume()

    }

When I load this "sftp.myserver.com" in the browser, I get a registration form similar to this. enter image description here

+4
source share
2 answers

From the NSURLSessiondocumentation:

NSURLSession , , ftp, http, https URL-, - SOCKS, . URL- ( ).

sftp.

+1

, NSURLSession. , auth.

. , ; , , ;

    class ViewController: UIViewController,NSURLSessionDelegate,NSURLSessionTaskDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.startConnection()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func startConnection () {
        let END_POINT_URL = "http://sftp.dewdrive.com:80";
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config,delegate: self,delegateQueue: nil)

        let url = NSURL(string: END_POINT_URL)
        let task = session.dataTaskWithURL(url!) {
            (let data, let response, let error) in
            // data - nil, response - nil
        }

        task.resume()

    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {

        let authMethod = challenge.protectionSpace.authenticationMethod;

        if authMethod == NSURLAuthenticationMethodServerTrust {

            let credential = NSURLCredential(trust: challenge.protectionSpace.serverTrust!);
            let disposition = NSURLSessionAuthChallengeDisposition.UseCredential;
            completionHandler(disposition,credential);

        } else if authMethod == NSURLAuthenticationMethodDefault || authMethod == NSURLAuthenticationMethodHTTPBasic  || authMethod == NSURLAuthenticationMethodNTLM {

            let server = challenge.protectionSpace.host;
            let alert = UIAlertController(title: "Authentication Required", message: "The Server \(server) requires username and password", preferredStyle: UIAlertControllerStyle.Alert);


            alert.addTextFieldWithConfigurationHandler({ (textField:UITextField) -> Void in
                textField.placeholder = "User Name";
            })
            alert.addTextFieldWithConfigurationHandler({ (txtField) -> Void in
                txtField.placeholder = "Password";
                txtField.secureTextEntry = true;
            })

            alert.addAction(UIAlertAction(title: "Log In", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
                let username = alert.textFields?.first?.text;
                let pwd = alert.textFields?.last?.text

                let credential = NSURLCredential(user: username!, password: pwd!, persistence:NSURLCredentialPersistence.ForSession);

                completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,credential);


            }))

            alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (action) -> Void in
                completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge,nil );

            }))

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.presentViewController(alert, animated: true, completion: { () -> Void in

                });

            })

        }
    }
}

, ; .

EDIT: ,

+1

Source: https://habr.com/ru/post/1611666/


All Articles