0

I'm fairly new to Swift and also very new to JSON and REST. I'm try to validate the credentials passed by the user and validate that the credentials are valid then print some of the JSON data to the screen. Everything I find online about this seems to involve simple a json api url with an api key without any credentials.

Basically I've got a url like this: https://ipaddresshere/yii_entry.php/rest/info And I will be user a username such as: Bob and a password such as: examplePass.

If someone could show me an example in swift of how to get data with authentication or point me in the right direction that would be great. Thanks!

user3459799
  • 345
  • 6
  • 16
  • The link you provided isn't a valid URL... What API are you using? They should have documentation to show what the response will be for either error or success. – RhapX Aug 05 '15 at 19:14
  • @RhapX sorry stackoverflow formatting. I updated it now. – user3459799 Aug 05 '15 at 19:23
  • This is usually done with a POST. Do you need JAVA help with the REST or JSON parsing. If you need to parse some JSON for a post request like a login I can help with that. – modesitt Aug 05 '15 at 21:24

1 Answers1

2

This login request, and a regular post. This relies on a file called SwiftyJSON. I recommend you download it and add it to your project for any JSON parsing. https://github.com/SwiftyJSON/SwiftyJSON. Try downloading a browser extension in chrome called postman to work with JSON and REST. This is an example post request for a login and a generic post request. These go in a modal swift file.

func loginRequest(username: String!, password: String!, completionHandler: ((NSURLResponse!, JSON, NSError?) -> Void)) {
        var request : NSMutableURLRequest = NSMutableURLRequest()
        let url: String! = "http://yourRestURL/login/\(username)/\(password)"
        println(url)
        request.URL = NSURL(string: url)
        request.HTTPMethod = "POST"
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) in
            var json = JSON(data: data!)
            println(json)
            completionHandler(response, json, error)
        })
    }

func postRequest(resourceURL: String!, completionHandler: ((NSURLResponse!, JSON, NSError?) -> Void)) {
        var request : NSMutableURLRequest = NSMutableURLRequest()
        request.URL = NSURL(string: resourceURL)
        request.HTTPMethod = "POST"

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) in
            var json = JSON(data: data!)
            completionHandler(response, json, error)
        })

If you insist on GET: The resource URL is the URL of the get request.

func getRequest(resourceURL: String!, completionHandler: ((NSURLResponse!, JSON, NSError?) -> Void)) {
        var request : NSMutableURLRequest = NSMutableURLRequest()
        request.URL = NSURL(string: resourceURL)
        request.HTTPMethod = "GET"

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) in
            var json = JSON(data: data!)
            completionHandler(response, json, error)
        })

    }

Usage: In your VC:

 func parseLoginRequest (usernameGiven: String, passwordGiven: String, sender: AnyObject?) {
        println("parsing")

        modal.loginRequest(usernameGiven, password: passwordGiven) { (response, json, error) in
            // parse it :) 

 })
modesitt
  • 7,052
  • 2
  • 34
  • 64
  • Trying the loginRequest function and I am having some issues. I am trying to perform this against a https url in my private network. Also when navigating to the page I am presented with an self-signed certificate when first opening a browser session. I currently am trying this url: let url: String! = "https://\(ipAddressField.text)/yii_entry.php/rest/case/\(username)/\(password)" and I am experiencing the following error: NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9807) Any ideas? – user3459799 Aug 06 '15 at 16:43
  • @user3459799 that is a temporary error to the DNS. Make sure he certificates are on your device. Is the post successful with something like POSTMan? – modesitt Aug 06 '15 at 16:50
  • I've actually never heard of POSTMan until you said that and wow that's a cool web app! But everything works fine with POSTMan with BasicAuth set and with the correct username and password. Ex. https://127.0.0.1/yii_entry.php/rest/info Status = 200 – user3459799 Aug 06 '15 at 17:00
  • What does your parse request look like. – modesitt Aug 06 '15 at 17:01
  • loginRequest(usernameField.text, password: passwordField.text) { (response, json, error) in // parse it :) println("Did it work? Response:\(response) JSON:\(json.count) Error: \(error?.description)") } – user3459799 Aug 06 '15 at 17:02
  • Actually I just looked at POSTMan again and I was using a GET Request instead of POST. When I use POST with Basic Auth I get a 404 Error – user3459799 Aug 06 '15 at 17:10
  • That means your server is set up wrong. The server is made for get. Use get in the swift. – modesitt Aug 06 '15 at 17:11
  • I did replace request.HTTPMethod = "POST" with request.HTTPMethod = "GET" in the loginRequest function but I am still experiencing the same error. NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9807) By the way I really appreciate all the help so far! You're probably one of the most helpful people on stack that I've dealt with! :D – user3459799 Aug 06 '15 at 17:37
  • Do you know objective-c? The server is challenging you for authentication. IN objective-c you could add something like this http://stackoverflow.com/questions/23241872/nsurlconnection-cfurlconnection-http-load-failed-kcfstreamerrordomainssl-9813 – modesitt Aug 06 '15 at 17:54
  • I do know objective-c. I'll give it a try later when I can find some more time to play around with this. I may end up trying something with Alamofire or AFNetworking I think as well. – user3459799 Aug 06 '15 at 19:45
  • Yeah those are great libraries. Sorry for any difficulty. – modesitt Aug 06 '15 at 20:33