2

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 ?

Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
JeanEdern
  • 46
  • 2
  • You don't get result in a Playground because of `sendAsynchronousRequest`. There's a trick, though: add `XCPSetExecutionShouldContinueIndefinitely()` at the end of your code, it should work. – Eric Aya Apr 28 '15 at 15:21
  • I just found the post where I read that: http://stackoverflow.com/a/24066317/2227743 – Eric Aya Apr 28 '15 at 15:22
  • Thanks. I was looking at something wrong with the code but I forgot to allow asynchronous code in playgrounds. – JeanEdern Apr 28 '15 at 15:34
  • Yeah, sorry, I can't help for your problem. I just thought it was important to explain why the connection didn't work in the Playground. :) – Eric Aya Apr 28 '15 at 15:36
  • Thanks Eric, you were right. It works now. my mistake for the asynchronous call on a playground. – JeanEdern Apr 28 '15 at 15:38

0 Answers0