Kodeco Forums

Alamofire Tutorial: Getting Started

In this Alamofire tutorial, you'll learn how to build an iOS app with Swift that sends & receives data to a remote API via HTTP using the Alamofire library.


This is a companion discussion topic for the original entry at http://www.raywenderlich.com/121540/alamofire-tutorial-getting-started
1 Like

Nice tutorial! Just what i needed to get started with Alamofire. Thank you very much!

1 Like

You’re definitely welcome! Thanks for the feedback :slightly_smiling:

Super tutorial. Thanks a lot! Especially for part about creating API Router.

1 Like

Very good tutorial.
Thanks a lot.
One question: how I can use language for tags from this project?

I added in ImaggaRouter.swift code:

case Language(String)
…
case .Language(“ru”): //this error
return (“/language”, .GET) // —//—//—

1 Like

@a_kant Probably something like this:

public enum ImaggaRouter: URLRequestConvertible {
  static let baseURLPath = "http://api.imagga.com/v1"
  //TODO: Replace xxx with your auth token found at https://imagga.com/profile/dashboard
  static let authenticationToken = "Basic xxx"
  
  case Content()
  case Tags(String, String)
  case Colors(String)

  public var URLRequest: NSMutableURLRequest {
    let result: (path: String, method: Alamofire.Method, parameters: [String: AnyObject]) = {
      switch self {
      case .Content():
        return ("/content", .POST, [String: AnyObject]())
      case .Tags(let contentID, let language):
        let params = [ "content" : contentID, "language" : language ]
        return ("/tagging", .GET, params)
      case .Colors(let contentID):
        let params = [ "content" : contentID, "extract_object_colors" : NSNumber(int: 0) ]
        return ("/colors", .GET, params)
      }
    }()

    let URL = NSURL(string: ImaggaRouter.baseURLPath)!
    let URLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(result.path))
    URLRequest.HTTPMethod = result.method.rawValue
    URLRequest.setValue(ImaggaRouter.authenticationToken, forHTTPHeaderField: "Authorization")
    URLRequest.timeoutInterval = NSTimeInterval(10 * 1000)

    let encoding = Alamofire.ParameterEncoding.URL

    return encoding.encode(URLRequest, parameters: result.parameters).0
  }

}
1 Like

Tomorrow I try it. And inform you.
Thank you.

It’s work fine.
Thanks a lot.

P.S.
I added code:
func downloadTags(contentID: String, completion: ([String]) → Void) {
Alamofire.request(ImaggaRouter.Tags(contentID, “ru”))
.responseJSON { }

1 Like

Thanks for the tutorial. I’ve been working with Alamofire since it’s beginning. But creating the router was new to me. I will surely make use of that in my future projects.

1 Like

It’s great tutorial to learn about Alamofire.
Thank you.

Thanks so much for this very Nice Tutorial.
Actually I revised a lot of Swift skills because of this tutorials and write downed them in Text file.
I can send it to you if you want, just send me your email.
my email is: ahmad.3atef@gmail.com

I’ll use Router concept in my next swift code, specially in Business Logic Layer as I was using it in Objective C.
:wink:

Thanks So much

For some beginners like me could you please add a delay i found it helpful before performing the segue
i used the code below it helped me to better understand the interactions

  self.delay(2.0) {
    self.performSegueWithIdentifier("ShowResults", sender: self)
    }

in imagePickerController(_:didFinishPickingMediaWithInfo info:) in the 4th part
:]

Hi, this might be a bit of topic, but here goes:
I have developed an app where an admin user can controll the app content (text, pictures, events etc) from a backend/CMS system. However the transfer of the data does not take place untill the user opens the app (every time the app is opened it goes to the backend to look for updates). I would like to push the data immediately so the user do not have to wait for the download to take place when the app is opened. So my question is how: Can I force the data to the app immediately after a backend update? I think it could be implemented with a special type of push messages that will trigger the app to search the backend for updates, but I would like to hear you if you have other ideas for how this functinality can be implemented?
Thanks :slight_smile:
Claus

Hi Claus - Yeah that’s a little off topic but I don’t mind giving you some direction. You are correct, background push notifications with fetch is the right way to go. You can also configure your app to do a scheduled background fetch but the interval is not guaranteed by iOS and is dependent on a lot of conditions you have no control over. I’d look into implementing a push notification with background fetching. Do remember that the user can shut off background fetch for your app so make sure you don’t make the app completely contingent on this feature.

How do you get the ACTUAL server json file using alamofire. Something like

{
“responseHeader”: {
“status”: 0,
“QTime”: 61,
“params”: {
“q”: “firstName:Shaantnu”,
“indent”: “true”,
“wt”: “json”,
“_”: “1464028787952”
}
},
“response”: {
“numFound”: 1,
“start”: 0,
“docs”: [{
“caseTypes”: [
“Pre-Litigation Mediation”,
“Civil Laws”,
“Family Dispute”,
“Divorce”,
“Marriage Laws”,
“Dowry Issues”,
“Women Help & Safety”,
“HUF or Joint Family Law”,
“Muslim Laws”
],

and not

{
response = {
docs = (
{
“version” = 15352wqwd18967678812160;
active = (
1
);
email = (
“me@me.com”
);
firstName = (
Nehlo
);
id = NehloTestUser1464098899306;
lastName = (
Test
);
mode = (
User
);
password = (
wear21zero
);
}
);

why I don’t see [unowned self] or [weak self] in this closure? This app will leak memory right, Ray.

self.downloadTags(firstFileID) { tags in
self.downloadColors(firstFileID) { colors in
completion(tags: tags, colors: colors)
}
}

I can update the code to include [weak self] - it looks like at some point [unowned self] is used in the uploader which could crash if self is nil. The chance of a leak happening in the example is pretty minimal but I’ll update it for those using the example code as a basis for their own projects.

Actually I’m not really sure a retain cycle is possible here given the block is local to the function itself.

Hi, Great tutorial so far (I’m almost done)!

I had some trouble with the tutorial, though, probably because I lean a little newb. The location of where to put this code wasn’t immediately clear:

Next, add the following code to upload.responseJSON:

I think it would be clearer to say: Next, add the following code after “upload.responseJSON { response in” or similar verbiage.

It’s also not clear to me where this location is:

Next, go back to uploadImage(_:progress:completion:) and replace the call to the completion handler in the success condition with the following: