How to use Last.fm API?

0

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

My question is: how do I do this with Swift . I'm a beginner, so I do not quite understand how to make this request with POST and HTTPS that they say. The whole API is based on this, so if I see an example of it, I can do everything else.

    
asked by anonymous 19.07.2015 / 17:54

1 answer

1

Ismael, you basically need to perform requests to the API that can be easily made using NSURL , NSURLRequest and NSURLSession . These three are preferably from iOS 7 , otherwise there is also NSURLConnection .

Following an example of API REST request , you log in and set the URL that the request 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 return because it is easier to manipulate the result in JSON than in XML , but you can remove this parameter if prefer.

Now, as the API indicates, you should use POST , so you define the 4 mandatory parameters ( clear, replace XXX with the actual values >) for the request and 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 you've done this, you just have to make the request and your return will be in JSON , as we defined above, and the string strData you manipulate as is required:

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()
    
20.07.2015 / 14:56