UIWebView doesn't load some link - iphone

hello
I'm trying to write an rss feed viewer for my iPhone. In my DetailView I have a UIWebView where I want to display specific link retrieved with the rss item.:
NSString* url = [data objectForKey:#"link"];
NSString *encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
NSLog(#"Selected link:%#",url);
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:encodedUrl]];
[itemWebpage loadRequest:request];
[request release];
now,if the retrieved link is something like
www.shazaam.com
it works. But as soon as the link is something like:
http://www.shazam.com/music/web/track?id=41970148"
it doesn't. I suppose it's because of the parameter...but how can I fix the problem????
thanks a lot!
elos

stringByAddingPercentEscapesUsingEncoding: is for when you want to put a string into a query variable. You don't need to do it for entire URLs. The question mark is being encoded when it shouldn't be, so you are getting a 404. Don't encode the URL and you should be fine.

Related

Get Facebook profile pic using 3.0 SDK

I'm having trouble getting the user's profile pic with the new Facebook SDK. All the answers on here use methods from the old SDK that no longer work.
I've tried using the FBProfilePictureView recommended in Facebook's tutorial, but this picture doesn't get cached and I don't think it can be converted into a UIImage.
Can anyone please provide some help? Thanks!
OK, I finally got this using the following:
imageData = [[NSMutableData alloc] init]; // the image will be loaded in here
NSString *urlString = [NSString stringWithFormat:#"http://graph.facebook.com/%#/picture?type=large", user.id];
NSMutableURLRequest *urlRequest =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:2];
// Run request asynchronously
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest
delegate:self];
if (!urlConnection)
NSLog(#"Failed to download picture");
Then I used -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data and -(void)connectionDidFinishLoading:(NSURLConnection *)connection to put the image together.
Best solution i've found:
I've used UIImage from AFNetworking https://github.com/AFNetworking/AFNetworking. It handles redirect and caching so you can fetch profile picture for every user id you have.
NSString *imageUrl = [NSString stringWithFormat:#"http://graph.facebook.com/%#/picture", ((NSDictionary<FBGraphUser> *) [self.friends objectAtIndex: indexPath.row]).id];
[friendCell.imageView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:#"profile.jpg"]];
Use https://github.com/rs/SDWebImage to cache the image. The URL to request the image should be
NSString *string = [NSString stringWithFormat:#"https://graph.facebook.com/%#?fields=picture", userid];
Use the link:
https://graph.facebook.com/me?fields=picture
to get the current user's profile picture.
Facebook provides the Graph API explorer tool which can come in handy when you want to try queries or to check the returned output.
Here's a link to the User API Reference.
If your problem is related to "self.userPofilePicture.profileID = user.id;".
Then self.userProfilePicture return UIView so just take View and display in it.
Don't forgot add class FBProfilePictureView in Identity Inspector as well as [FBProfilePictureView class] to AppDelegate implementation file.
I hope this will helpful.

Extract XML from UIWebView

I'm trying to extract some XML from a UIWebView, and not having much luck. This is what the entire document looks like:
<?xml version="1.0" encoding="utf-8"?>
<authResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<firstName>Name here</firstName>
<lastName>Name here</lastName>
<membershipTier>Membership level</membershipTier>
<errorMessage />
<isValid>1</isValid>
</authResponse>
I have tried a number of variations of the stringByEvaluatingJavaScriptFromString method, but this is the only one that will return anything for me:
[webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.textContent"]
However, I need the raw XML, not the text content. Any suggestions?
EDIT: I have control over the XML, so it can be modified if need be.\
EDIT 2: As requested, code I am using to load the request is below. Note that this request is for a login screen. Once the user has entered their credentials, the page after that is the one I am trying to extract the results from. I determine which is the current page in webViewDidFinishLoad by testing the current mainDocumentURL for the UIWebView object.
NSString* urlString = kLoginURL;
NSURL* url = [NSURL URLWithString:urlString];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
UIWebView* tmpWebView = [[UIWebView alloc] init];
self.webView = tmpWebView;
[tmpWebView release];
self.webView.delegate = self;
[self.webView loadRequest:request];
Just wrote a little test program to figure this out (fun!). It loads the UIWebView contents via:
NSString * data = #"<?xml version=\"1.0\" encoding=\"utf-8\"?><authResponse xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><firstName>Name here</firstName><lastName>Name here</lastName><membershipTier>Membership level</membershipTier><errorMessage /><isValid>1</isValid></authResponse>";
[self.webview loadHTMLString: data baseURL: nil];
I then passed the string document.getElementsByTagName('body')[0].innerHTML to stringByEvaluatingJavaScriptFromString
and it returns what you want:
<authresponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><firstname>Name here</firstname><lastname>Name here</lastname><membershiptier>Membership level</membershiptier><errormessage><isvalid>1</isvalid></errormessage></authresponse>
i'd grab the whole html as a string on a seperate thread, or use this as the basis to load the webview:
NSString *xmlString = [NSString stringWithContentsOfURL:yourURL]
You can try using kissxml to retrieve the whole xml structure.
Or you can just save the response into a string from your NSURLRequest or if you are using other libraries to do a http connection
NSURL *url = [[NSURL alloc] initWithString:#"http://www.w3schools.com/xml/note.xml"];
NSString *myString = [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:(NSURL*)url] encoding:NSISOLatin1StringEncoding];
The code above is a sample on how you can retrieve the xml structure. This is much easier than using uiwebview. The sample xml encoding is using ISO-8859-1 so you have to set the correct encoding so that the data will be readable
I would suggest going with Nik's suggestion - get the request URL and get its content in an NSString.
OR you can send a request to the login URL (you are already intercepting the requests being sent) and get a response in a string.
If you want to read the entire body tag's content or the html and body tag's content, you might just do this
NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"];
or
NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString:#"document.all[0].innerHTML"];
You can use either of these as per your need:
NSString *html1 = [webView stringByEvaluatingJavaScriptFromString:
#"document.body.innerHTML"];
NSString *html2 = [webView stringByEvaluatingJavaScriptFromString:
#"document.documentElement.outerHTML"];

iphone: how to get text from web site and show it on application

i have web site that show a text and i update this text every day , i want to show this text on iphone application , how can i get this text from web site from application ?
what should i do ?
thanks
1-> you require to connect with your web server thought HTTP connection.
2-> Make the request to server.
3-> Parse server response that may contain your "Text".
For technical assistance Read below.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html
I don't recommend this as the best way to obtain a string from your own web server.
This should point you in the right direction, don't expect it to compile cleanly.
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
/* set headers, etc. on request if needed */
[request setURL:[NSURL URLWithString:#"http://example.com/whatever"]];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
NSString *html = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSScanner *scanner = [NSScanner scannerWithString:html];
NSString *token = nil;
[scanner scanUpToString:#"<h1>" intoString:NULL];
[scanner scanUpToString:#"</h1>" intoString:&token];
This will capture text from first h1 tag.
The simplest way is to create a REST API. That might sound tough but it's really easy. On the server side, create a new page which holds only the raw text. Usually it's best to keep it there in JSON/XML format, but a simple text will also work. Now from the iPhone, just contact that address and the response data will contain the text. Parsing an existing page is not something I recommend, because changing that page in the future might result in the app not working anymore.
This is a answer quite late but I think it still might help in your future. You can go into parsing the website and that is the right way to do it but I will show you how to do it a different way, this can also be used to read xml, html, .com, anything and also, .rss so it can read RSS Feeds.
Here :
This can get your first paragraph, if you request I will show you how to get the second paragraph and so on.
//This is your URL
NSURL *URL = [NSURL URLWithString:#"URL HERE"];
//This is the data your pulling (dont change)
NSData *data = [NSData dataWithContentsOfURL:URL];
// Assuming data is in UTF8. (dont change)
NSString *string = [NSString stringWithUTF8String:[data bytes]];
//Your textView your not done.
description.text = string;
//Do this with your textview
NSString *webStringz = description.text;
// Leave this
NSString *mastaString;
mastaString = webStringz;
{
NSString *webString2222 = mastaString;
NSScanner *stringScanner2222 = [NSScanner scannerWithString:webString2222];
NSString *content2222 = [[NSString alloc] init];
//Change <p> to suit your need like <description> or <h1>
[stringScanner2222 scanUpToString:#"<p>" intoString:Nil];
[stringScanner2222 scanUpToString:#"." intoString:&content2222];
NSString *filteredTitle = [content2222 stringByReplacingOccurrencesOfString:#"<p>" withString:#""];
description.text = filteredTitle;
}
Title ? Same deal change the <p> to a <title> in RSS <description> and <title>.
Image ? Same deal change the <p> to what ever your RSS or website uses to get a image to find
But remember for both of them when you change the` you see the link which says stringByReplacingOccurences of you have to change that as well.
out then you have to delete this and make your code like this :
/This is your URL
NSURL *URL = [NSURL URLWithString:#"URL HERE"];
//This is the data your pulling (dont change)
NSData *data = [NSData dataWithContentsOfURL:URL];
// Assuming data is in UTF8. (dont change)
NSString *string = [NSString stringWithUTF8String:[data bytes]];
//Your textView your not done.
description.text = string;
NLog(#"%#", string)
//Do this with your textview
NSString *webStringz = description.text;
// Leave this
NSString *mastaString;
mastaString = webStringz;
Now check your log it shows your whole website html or rss code then you scroll and read it and find your image link and check the code before it and change the String Scanner to your needs which is quite awesome and you have to change the stringByReplacingOccurences of.
Like I said images are a bit tricky when you do it with this method but XML Parsing is a lot easier ONCE you learn it , lol. If you request I will show you how to do it.
Make sure :
If you want me to show you how to do it in XML just comment.
If you want me to show you how to find the second paragraph or image or title or something just comment.
IF YOU NEED ANYTHING JUST COMMENT.
Bye have fun with code I provided, anything wrong JUST COMMENT! !!!!
:D

iphone SDK :How to add more string after an static URL?

First...if no one can answer this question it's ok...
because I don't know how to ask this question in the correctly description
my program is get the plist data from URL and show it on the iphone tableview
My colleagues give me two URL to get the plist data
So I have two tableviews(tableview1,tableview2)
two URLs(URL1,URL2)
My tableview1 via URL1 get a plist1 ,and tableview1 has 3 contents in first 3 rows
ex.(row0 id1),(row1 id2),(row2 id3)
When I select row0 ,it will jump to tableview2 and with a title id1 on the navgation bar
so far is I can do...
but at tableview2 ,it need a URL like: www.URL2.php?id=1 =>that means...
I have to add my tableview title after URL2
to get the right plist related the id 1
my question is .......URL2 is static,how to make it like dynamic to get the right URL address ???
well.....first time I thought my colleagues will give me a data like array of array
But it's not...I never try use URL like dynamic...
This is code in the tableview1 to let me get the plist from URL
NSURLRequest *theRequest=[NSURLRequest requestWithURL:appDelegate.URL1//I declare the URL at appDelegate.m for some reasons...
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSData *returnData = [NSURLConnection sendSynchronousRequest:theRequest
returningResponse:nil error:nil];
NSString *listFile = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];
self.array = [listFile propertyList];//I parse the data from array to tablecview
and this is how I parse the title from Tableview1 to Tableview2
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
TableView2 *tb2 = [[TableView2 alloc]init];
tb2.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
tb2.title = [[[array objectAtIndex:indexPath.row] valueForKey:#"name"]description];
[self.navigationController pushViewController:tb2 animated:YES]; }
Any ideas ?
well ...if someone can answer this or give me a direction I will very appreciate
Great Thanks for All Reply and Answers !!!
Oh...one more thing,I can use ASIHTTPRequest to post a data
but I don't know how to get data after post ...?(is this help ?)
Assuming you have a string that you want to append to appDelegate.URL1 declared as:
NSString *stringToAppend = #"whatever";
Then you can produce a string containing the new URL:
NSString *newURLAsString = [NSString stringWithFormat:#"%#%#",[appDelegate.URL1 absoluteString],stringToAppend];
And an NSURL from this string:
NSURL *newURL = [NSURL URLWithString:newURLAsString];
And the NSURLRequest from that:
NSURLRequest *theRequest=[NSURLRequest requestWithURL:newURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
I'm not exactly sure what you are trying to say.
You want to load tableView1 from www.foo.com then when the user clicks a row it directs to another URL such as www.foo.com/row0.
The easiest way to acomplish that would be to create a property that you set in your selectedRow method
Something along the lines of.
Declare the property in your header
#Property (readwrite,copy) NSString* strURL;
To append the String to api
when you want to pass some string to your Api as a parameter
For example I store the lat and long of user and then pass that string to API's url
NSURL *address1=[NSURL URLWithString:[NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=false",location]];
NSLog(#"your lat and long is::%#",[NSString stringWithFormat:#"http://api.wunderground.com/api/90caafb557ba6bf7/geolookup/conditions/forecast/q/%#.json",location]);
Here Location is a NSString which store the latitude and longitude and i pass that data to API to fetch City,Country and tempetature etc..
with the help of %# we can pass the stored value to api

I have a link to my terms and conditions data and I want to show this data by reading it

How do I read data from an USL link, and display it on my textview? The URL link content contains only normal text
I am using:
NSString *userAgreementStringURL = [NSString stringWithFormat:#"%#/requestConfigurationData.php?ownerID=%#&view=userAgreement", serverURL, ownerID];
NSURL *userAgreementURL = [NSURL URLWithString:userAgreementStringURL];
NSURLRequest *userAgreementRequest = [NSURLRequest requestWithURL:userAgreementURL];
userAgreementData = [[NSMutableData alloc] init];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
userAgreementConnection = [[NSURLConnection connectionWithRequest:userAgreementRequest delegate:self] retain];
[userAgreementTextView setText:[NSString stringWithContentsOfURL:#"http://medicinephone.com/dev2/visit/requestConfigurationData.php?ownerID=13&view=userAgreement" encoding:NSUTF8StringEncoding error:NULL]];
Show us your code. If you are trying what I think you are trying passing an array to text view's setText method won't work. You need to get the string from the array prior to that. If you array contains one word per array element you might want to try using componentsJoinedByString.
[myTextView setText:[NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://apple.com" encoding:NSUTF8StringEncoding error:NULL]]];
one line of code, thank you apple.
Edit: forgot to make a NSURL from the string.