Fabio Ferreira
Fabio Ferreira

Reputation: 44

Using a remote Plist

My app currently uses a Plist to display items in a TableView. The Plist resides inside the Bundle resources of the app. But now I want to be able to fetch the same PList from the web so I can update it anytime.

My current code:

func getItems() -> [Dictionary<String, AnyObject>]?{
    if let path = NSBundle.mainBundle().pathForResource("Items", ofType: "plist", 
        let itemsDictionary = NSDictionary(contentsOfFile: path),
        let items = itemsDictionary["biology"] as? [String:AnyObject]
    {
        return items["biology"] as? [Dictionary<String,AnyObject>]
    } else {
        return nil
    }
}

How could I implement a "downloadable" solution to retrieve the same Plist?

Upvotes: 0

Views: 591

Answers (2)

Jon Shier
Jon Shier

Reputation: 12770

It's a bit of overkill to import a whole dependency to solve a single issue, assuming you have no other networking needs in your app, but Alamofire has a plist decoder built in. It would be as simple as:

Alamofire.request(.GET, "https://yourserver.com").responsePropertyList { (request, response, result, error) in

}

Upvotes: 1

Richmond Watkins
Richmond Watkins

Reputation: 1370

A plist is just XML so parsing it will work the same. You'll just want to do a fetch with NSURLSession or NSURlConnection. Once you get a response you'll serialize that response into a NSDictionary with NSPropertyListSerialization.

Here is an old Obj-C I found that should do the trick. Translating it into Swift won't be hard

NSURL *url = [NSURLURLWithString:@"http://lab.vpgroup.com.br/aplicativos/teste-catalogo/lista.plist"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response,    NSData *data, NSError *connectionError) {
NSDictionary *dict = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:0 format:0 errorDescription:nil];
NSLog(@"%@", dict);
}]; 

Upvotes: 0

Related Questions