Get link MP3 from a web - ios

I want to get a MP3 link from a website, I don't know exactly what type of this website is, but it only has content like this (link: http://www.nhaccuatui.com/download/song/4Upyxq0QlytX)
{"error_message":"Success","data":{"stream_url":"http:\/\/download.s81.stream.nixcdn.com\/dd634cb8afcc15d7c17a8ce4c548709f\/533cc58e\/NhacCuaTui791\/KhongQuanTam-ChiDan_4cyw4_hq.mp3","is_charge":"false"},"error_code":0,"STATUS_READ_MODE":true}
What can I do if I want to get content (link mp3) from key (?) "stream_url" from this link to put it in to my iOS Applications?

If you rearrange your JSON it will look like this:
{
"error_message":"Success",
"data":{
"stream_url":"http:\/\/download.s81.stream.nixcdn.com\/dd634cb8afcc15d7c17a8ce4c548709f\/533cc58e\/NhacCuaTui791\/KhongQuanTam-ChiDan_4cyw4_hq.mp3",
"is_charge":"false"
},
"error_code":0,
"STATUS_READ_MODE":true
}
From that you can see its a dictionary.
If you want to get it via url request do something like this:
NSDictionary *dictionaryData;
NSURLRequest *requestURL = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.00];
NSHTTPURLResponse *response;
NSError *error = [[NSError alloc]init];
NSData *apiData = [NSURLConnection sendSynchronousRequest:requestURL returningResponse:&response error:&error];
dictionaryData = [NSJSONSerialization JSONObjectWithData:apiData options:kNilOptions error:&error];
Then you can get the url by doing this:
NSString *str = [[dictionaryData objectForKey:#"data"] objectForKey:#"stream_url"];
Then make another request for getting the file.

The data you presented is in JSON format. To access it, use NSJSONSerialization.

Related

Twitter iOS GET statuses/home_timeline using Parse

This will be my first iPhone app and I am running into difficulties that I thought I'd be able to find a tutorial on, but alas.... nothing on the inter webs that I can find.
I'm trying to get an initial 20 or so tweets from a signed in user (signed in using Parse's Twitter authentication) and I can't seem to get it to work. I put a breakpoint in when I get an error and this is what it shows:
I'm contemplating abandoning Parse all together and doing my own authentication using https://github.com/nst/STTwitter but wanted to quickly see if there was a way to simply do what I am trying to. The code is question is at this github: https://github.com/johndangerstorey/twiz and outlined below as found in my MyLoginViewController.m file:
NSString *bodyString = [NSString stringWithFormat:#"https://api.twitter.com/1.1/statuses/home_timeline.json?screen_name=johnDANGRstorey"];
// Explicitly percent-escape the '!' character.
bodyString = [bodyString stringByReplacingOccurrencesOfString:#"!" withString:#"%21"];
NSURL *url = [NSURL URLWithString:bodyString];
NSMutableURLRequest *tweetRequest = [NSMutableURLRequest requestWithURL:url];
tweetRequest.HTTPMethod = #"GET";
tweetRequest.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[[PFTwitterUtils twitter] signRequest:tweetRequest];
NSURLResponse *response = nil;
NSError *error = nil;
// Post status synchronously.
NSData *data = [NSURLConnection sendSynchronousRequest:tweetRequest
returningResponse:&response
error:&error];
// Handle response.
if (!error) {
NSLog(#"Response: %#", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
} else {
NSLog(#"Error: %#", error);
}
Thanks for your reply and help.
I figured it out, GET requests don't require .body or .method requests so I just removed
tweetRequest.HTTPMethod = #"GET";
tweetRequest.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
and was golden.

Showing PhpMyAdmin database in iOS uitableview

I am creating a app in which I want to fetch data from PhpMyAdmin database to my UITableView.
Is there any good tutorial for this purpose? Please not any chat app tutorials I simply want to display my table in tableview.
My table has 5 fields (id, fname, lname, email, address).
Thank you
The best way to handle it is to create a JSON API for your database and then make your iOS app parse the JSON data.
Here is an example of how to create a JSON output from MySQL using PHP.
When you have your JSON output you should download it from the app using the NSURLConnectionand NSJSONSerialization, something like this:
NSURL* url = [NSURL urlWithString:#"http://yourapi.url/here"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError **error = nil;
NSData *data = [[NSData alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error]];
NSInteger httpStatus = [((NSHTTPURLResponse *)response) statusCode];
NSLog(#"responsecode:%d", httpStatus);
NSDictionary *parsedJSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorInfo];
The content of your JSON will be placed in the parsedJson dictionary.
This is just a quick example of using a synchronous request with NSURLConnection. If you want a asynchronous solution you should read the documentation on NSURLConnection.
To show the data in a UITableView you should checkout this tutorial.

message:(#200) App does not have permission to make this call in ios application using facebook sdk

I want to like and comment in my iOS application.But the problem is whenever I call my API the response comes in the form of this `error:message:(#200)'. App does not have permission to make this call and sometimes it will give input parameter is required.The permissions i give are 'basic_info','email','user_likes' and 'read_stream'. I am passing object id and access token in my like and comment API.
Like API code:
NSString *theWholeUrl = [NSString stringWithFormat:#"https://graph.facebook.com/%#/likes?access_token=%#",self.friendId,[FBSession activeSession].accessTokenData.accessToken];
NSLog(#"Value of theWholeUrl%#",theWholeUrl);
NSURL *facebookUrl = [NSURL URLWithString:theWholeUrl];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:facebookUrl];
[req setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
You need the publish_actions permission to be able to like and comment on content programmatically via the API.

How to parse JSONP in Objective-C?

I am retrieving JSON information for an API and it says on the API that it is in JSON but I noticed it is in JSONP or "json with padding" as some call it. I tired to look everywhere to find how to parse this but no luck. The information I am trying to receive is this:
({"book":[{"book_name":"James","book_nr":"59","chapter_nr":"3","chapter":
{"16":{"verse_nr":"16","verse":"For where envying and strife is, there is confusion and
every evil work."}}}],"direction":"LTR","type":"verse"});
The link to the data is https://getbible.net/json?p=James3:16, so you can look at it directly.
This is the code I am using to try to retrieve the JSON Data and parse it into a NSMutableDictionary.
-(void)fetchJson {
NSString *currentURL = [NSString stringWithFormat:#"https://getbible.net/json?p=James"];
NSURL *url = [NSURL URLWithString:currentURL];
NSData *data = [[NSData alloc]initWithContentsOfURL:url];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
NSMutableData *receivedData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
[receivedData setLength:0];
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:url MIMEType:#".json" expectedContentLength:-1 textEncodingName:nil];
expectedTotalSize = [response expectedContentLength];
if ([data length] !=0) {
NSLog(#"appendingData");
[receivedData appendData:data];
if(connection){
NSLog(#"Succeeded! Received %lu bytes of data",(unsigned long)[receivedData length]);
}
NSError *error;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if(jsonResponse){
NSArray *responseArr = [jsonResponse mutableCopy];
NSLog(#"%lu",(unsigned long)[responseArr count]);
}else if (!jsonResponse){
//do internet connection error response
}
}
}
The results I am getting back from putting a breakpoint in the code is:
jsonResponse returns NULL
NSError NSCocoaErrorDomain code - 3840
but my NSData *data is returning 15640 bytes.
My console is displaying this from the NSLogs I used for debugging:
2014-04-20 01:27:31.877 appendingData
2014-04-20 01:27:31.879 Succeeded! Received 15640 bytes of data
I am receiving the data correctly but I am not parsing it correctly I know the error is because the JSON is in JSONP format. If anyone could please help with this I would appreciate it so much. I have tired to give as much detail on this question as I can but if you need more information just let me know so I can add it and make this as clear as possible.
Your code has at least two separate attempts to download the data. Neither is really correct. The code also only works with JSON, not JSONP.
Try this:
NSURL *url = [NSURL URLWithString:#"https://getbible.net/json?p=James"];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data) {
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSRange range = [jsonString rangeOfString:#"("];
range.location++;
range.length = [jsonString length] - range.location - 2; // removes parens and trailing semicolon
jsonString = [jsonString substringWithRange:range];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&jsonError];
if (jsonResponse) {
// process jsonResponse as needed
} else {
NSLog(#"Unable to parse JSON data: %#", jsonError);
}
} else {
NSLog(#"Error loading data: %#", error);
}
}];
One problem is that the data you're downloading has extraneous information at the beginning and end. The JSON being delivered by your URL is:
({"book":[{"book_name":"James","book_nr":"59","chapter_nr":"3","chapter":{"16":{"verse_nr":"16","verse":"For where envying and strife is, there is confusion and every evil work."}}}],"direction":"LTR","type":"verse"});
As the error message you're seeing indicates: you need to remove the initial ( from the beginning of the string and the ); from the end so that your JSON will start with the dictionary that your code expects. You can do this by calling subdataWithRange: on your NSData object:
NSData* jsonData = [data subdataWithRange:NSMakeRange(1, data.length-3)];
NSDictionary* jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData
options:0
error:&error];
Just to update everyone, the NSURLRequest has been deprecated in iOS9. I tried the answer by #rmaddy, and I didn't receive anything either (just like what #lostAtSeaJoshua was encountering I guess). I have updated rmaddy's answer to reflect the NSURLSession implementation that has (I think) replaced NSURLRequest:
NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:#"http://somerandomwebsite.com/get.php?anotherRandomParameter=5"];
[[session dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
// handle response
if (data) {
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"stringJSONed: %#",jsonString);
//Do something with the received jsonString, just like in # rmaddy's reply
} else {
NSLog(#"Error loading data: %#", error);
}
}] resume];
Just a heads up notice, when I first ran it, it gave me the security error. What you need to do (if you are using http) is to add this to your plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
I have to mention that after the NSAllowArbitraryLoads key, there are most probably other keys and values, such as NSExceptionDomain. But they're not really relevant to this answer I think. If you need to look further, let me know and I will dig deeper :)

simple mantle JSON example from URL

I have have some trouble in understanding what is needed to fetch a JSON file with mantle.h from a URL.
Can someone give me an example of how it works?
For example:
-I have a URL www.example.com with a JSONFile as follows:
{
"name": "michael"
}
How could I fetch it?
I use this process for fetching JSON:
NSURL *s = url;//Put your desird url here
NSURLRequest *requestURL = [NSURLRequest requestWithURL:s cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.00];
NSHTTPURLResponse *response;
NSError *error = [[NSError alloc]init];
NSData *apiData = [NSURLConnection sendSynchronousRequest:requestURL returningResponse:&response error:&error];
dictionaryData = [NSJSONSerialization JSONObjectWithData:apiData options:kNilOptions error:&error];
Now the dictionaryData contains your JSON. You can fetch it by:
NSString *name = [dictionaryData valueForKey:#"name"];
And make sure you are making async request. For this put the code within this block:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
//Put the code here
});
Hope this helps.. :)
Call it with following method
[super getRequestDataWithURL:urlString
andRequestName:sometext];
You will get response in the following method if successful
- (void)successWithRequest:(AFHTTPRequestOperation *)operation withRespose:(id)responseObject withRequestName:(NSString *)requestName {
NSString *response = operation.responseString;
id jsonObject = [response objectFromJSONString];
if(![super checkforServerRequestFailureErrorMessage:jsonObject]) {
[self.leaderboardProxyDelegate leaderboardListSuccessful:jsonObject];
}
}
You will get dictionary in jsonObject

Resources