How to use Last.fm API?

Asked

Viewed 216 times

0

I need to make an iOS app that works with Last.fm API and it all starts out by making a request to authenticate the user.

My question is: how do I do it with Swift. I’m a beginner, so I don’t quite understand how to make this request with POST and HTTPS what they say. The entire API is based on this, so if I see an example like this, I can do everything else.

1 answer

0


Ismael, what you need basically is to perform requisitions for the API which can be done easily using NSURL, NSURLRequest and NSURLSession. These three are preferably from the iOS 7, otherwise there is also the NSURLConnection.

Following an example of REST request from API, you log in and set the URL that the requisition will be made:

var session = NSURLSession.sharedSession()
var request = NSMutableURLRequest(URL: NSURL(string: "https://ws.audioscrobbler.com/2.0/?method=artist.getSimilar&format=json")!)

Note that I used format=json for the return, as it is easier to manipulate the result in JSON than in XML, but you can remove this parameter if you prefer.

Now, as indicated by API, you must use POST, then you set the 4 mandatory parameters (of course, replace XXX with the actual values) for the requisition and the method:

var params = "api_key=XXX&api_sig=XXX&username=XXX&password=XXX".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!

request.HTTPMethod = "POST"
request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)

Once this is done, just make the request and your return will be on JSON, as we defined above, and the string strData you manipulate in any way necessary:

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    var strData = NSString(data: data, encoding: NSUTF8StringEncoding)

    if error == nil {
        // sucesso
    } else {
        // falha
    }
})

task.resume()
  • Perfect explanation, it was very clear. I thank you for your help!

  • If you have answered your question, consider marking it as correct, so it will help others with your same need ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.