Rocking Me
Rocking Me

Reputation: 162

Coudn't load JSON while calling api in Swift

I have my own api for an application. I was trying to call the api and i need to get the json data as the response. Here is my code

import Cocoa

class ViewController: NSViewController {

@IBOutlet weak var EmailText: NSTextField!

@IBOutlet weak var PasswordText: NSSecureTextField!
@IBAction func signin(sender: AnyObject) {
    println("email is \(EmailText.objectValue) and Password is \(PasswordText.objectValue)")

    var url : String = "https:username:[email protected]/api/v3/auth/token/"
    var request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: url)
    request.HTTPMethod = "GET"

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
        let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

        if (jsonResult != nil) {
            println("\(jsonResult)")
        } else {
            println("Couldn't load json")
        }


    })
}
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override var representedObject: AnyObject? {
    didSet {
    // Update the view, if already loaded.
    }
}
}

The jsonResult should give me the apikey as the json data.

But the else condition was showing for me while running the mac app. As I was very new for the swift and also for building the mac app, I was not able to overcome with this.

Upvotes: 2

Views: 231

Answers (2)

user4423327
user4423327

Reputation:

This is the duplicate of this error: Error Domain=HTTPTask Code=404 "page not found" UserInfo=0x608000228720 {NSLocalizedDescription=page not found} I think. Anyways as I said for that question please check below.

You are using the format [email protected]:[email protected]/com/.... which works while you are working in Javascript or Jquery.

In Swift, it doesn't takes in the basic-auth. For the basic auth, we have to send with the encode string to the authentication url like:

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let userPasswordString = "\(Email.stringValue):\(Password.stringValue)"
    let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
    let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions(nil)
    let authString = "Basic \(base64EncodedCredential)"
    println("\(authString)")
    config.HTTPAdditionalHeaders = ["Authorization" : authString]
    let session = NSURLSession(configuration: config)



    let url = NSURL(string: "https://api.domain.com/api/v2/auth/token/")
    let task = session.dataTaskWithURL(url!) {
        (let data, let response, let error) in
        if let httpResponse = response as? NSHTTPURLResponse {
            let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
}
}

After then just print the data and see it will definitely meets your question.

Upvotes: 1

Laurent Rivard
Laurent Rivard

Reputation: 519

As @houguet pierre mentioned, you could use Alamofire, it will handle the JSON object if you get one, and also alert you if you don't. This code is the simplest case, and probably enough for what you need.

Alamofire.request(.GET, url) .responseJSON { (_, _, JSON, error) in if error == nil { println(JSON) } else { println(error.localizedDescription) }

Upvotes: 1

Related Questions