Search code examples
iosobjective-cnsurl

How to pass an array in an url query parameter using nsurl in objective-c?


The API need to pass an array in an url query parameter, how to acheive this in iOS?

I only know how to pass a single vaue, like the API below : ?title=Design Milk&id=feed/http://feeds.feedburner.com/design-milk

API sample:

  "title": "Design Milk",
  "id": "feed/http://feeds.feedburner.com/design-milk",
  "categories": [
    {
      "id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/design",
      "label": "design"
    },
    {
      "id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/weekly",
      "label": "weekly"
    },
    {
      "id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/global.must",
      "label": "must reads"
    }
  ]

Solution

  • Create a collection and then use NSJSONSerialization to create JSON data representation. Use the resulting data as the POST data.

    NSDictionary *parameters = @{
      @"title": @"Design Milk",
      @"id": @"feed/http://feeds.feedburner.com/design-milk",
      @"categories": @[
              @{
                  @"id": @"user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/design",
                  @"label": @"design"
                  },
              @{
                  @"id": @"user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/weekly",
                  @"label": @"weekly"
                  },
              @{
                  @"id": @"user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/global.must",
                  @"label": @"must reads"
                  }
              ]
    };
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictData options:0 error:&error];