I am trying to get an IUAlertview to display with a custom message pulled from a website upon loading the app. I have control of the website, so the idea is if I want to change the message, I can just change the website. This morning I asked about how to update a personalized message, and this idea was the result, but now that I am trying to code it, I am getting errors.
After browsing other initWithContentsOfURL questions on stack overflow, I came up with the following code:
NSStringEncoding *encoding = NULL;
NSError *error;
NSString *myHtml = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.gcsp.webuda.com/hi.htm"] usedEncoding:encoding error:&error];
UIAlertView *message1 = [[UIAlertView alloc] initWithTitle:myHtml
message:myHtml
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[message1 show];
I put with in the viewWillAppear
method and it does trigger when the user opens the app. However, the UIAlertview message and title are blank, and the app reports no errors. Can someone please help me figure out why my code isn't working?
I really appreciate the help!!
If you know the encoding of the text on the website will always be the same, you can use the method:
- (id)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
instead.
I'd also suggest performing network operations in the background:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),
^{
NSError *error;
NSString *myHtml = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.gcsp.webuda.com/hi.htm"] encoding:NSUTF8StringEncoding error:&error];
UIAlertView *message1 = [[UIAlertView alloc] initWithTitle:myHtml
message:myHtml
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
//UI updates should be on main thread
dispatch_async(dispatch_get_main_queue(),
^{
[message1 show];
});
});