I've coded an api on a rails project and an app using Swift on Xcode 6.3 The api is proteced by a username and a password, using basic authentification.
class Api::V1::RestaurantsController < ApplicationController
http_basic_authenticate_with name: "api", password: ENV['API_SECRET']
The API and the authentification work fine on my localhost. But I can't code the call on my iOS app for iphone. I am quite new to Xcode, but I would like to make the API call, passing the username and password, and getting the json back. The code is:
var latitude = 48.858564
var longitude = 2.294476
let PasswordString = "api:1234" //username:password
let PasswordData = PasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64EncodedCredential = PasswordData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
let urlPath: String = "http://localhost:3000/api/v1/restaurants?latitude=\(latitude)&longitude=\(longitude)"
var url: NSURL = NSURL(string: urlPath)!
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
request.HTTPMethod = "GET"
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println("\(jsonResult)")
})
I tried this code on a playground but I don't get any result. Would you have any idea on how to make the HTTP call passing the username and password ?