How to display a image when there is no internet connection (web view) - xcode

I have a web view based program I was just testing. How do you display a image when there is no internet connection?
I have a basic webview
//
// XYZViewController.m
// Phantomore
//
// Created by Kevin Jin on 5/15/14.
// Copyright (c) 2014 Kevin Jin. All rights reserved.
//
#import "XYZViewController.h"
#interface XYZViewController ()
#end
#implementation XYZViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *fullURL = #"http://www.phantomore.com";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
#end
Thats it,I just want to know what I have to do to have it displaying a image when tehre is no internet connection

I just simplified mamnun answer(Get Reachability here).
You can use this method after you have implemented the reachability class
- (BOOL)isConnectedToInternet
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return !(networkStatus == NotReachable);
}
In any of your class
- (void)viewDidLoad
{
[super viewDidLoad];
if([self isConnectedToInternet]){
//Hide your imageview
NSString *fullURL = #"http://www.phantomore.com";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];
}
else{
// Hide your webview
// Show your imageview
// Do not forget to import reachability class on top
}
}

There is two way of doing it.
Before even performing the url request, check if internet connection is available. Use Apple provided Reachability classes or better yet use the open-source version. If internet is available load the request. If not add an UIImageView with your preferred UIImage as a subview of the webview. You can do something like this:
//inside #interface
#property(nonatomic, strong) UIImageView *imageView;
//inside -(void)viewDidLoad
self.imageView = [UIImageView alloc] initWithImage:[UIImage imageNamed:#"as.as"];
Reachability* reach = [Reachability reachabilityWithHostname:#"www.google.com"];
reach.reachableBlock = ^(Reachability*reach) {
// load request
NSString *fullURL = #"http://www.phantomore.com";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];
};
reach.unreachableBlock = ^(Reachability*reach) {
//show imageview
[_viewWeb addSubView:self.imageView];
};
[reach startNotifier];
Implement UIWebView delegate. In the – webView:didFailLoadWithError: method, check the error. If the error is caused by no internet connection, add the imageview(same as before).

Related

no visible #interface for 'UIImagePickerController

So my code says
no visible #interface for UIImagePicker Controller
I am using a Tab View Controller
My code for my FirstViewController.m is
#import "FirstViewController.h"
#interface FirstViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
UIImagePickerController *bailey;
UIImagePickerController *baileys;
UIImage *image;
IBOutlet UIImageView *imageView;
}
- (IBAction)takePhoto;
- (IBAction)chooseExisting;
#end
#implementation FirstViewController
- (IBAction)takePhoto {
bailey = [[UIImagePickerController alloc]init];
bailey.delegate = self;
[bailey setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:bailey animated:YES completion:NULL];
}
- (IBAction)chooseExisting {
baileys = [[UIImagePickerController alloc] init];
baileys.delegate = self;
[baileys setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:baileys animated:YES completion:NULL];
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
[imageView setImage:image];
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void) imagePickerControllerDidCancel:(UIImagePickerController *)bailey {
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (IBAction)ShareFB {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
slComposeViewController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[slComposeViewController addImage:[UIImage imageNamed:#"image"]];
[slComposeViewController addURL:[NSURL URLWithString:#"http://www.agfg.com.au"]];
[self presentViewController:slComposeViewController animated:YES completion:NULL];
//I borrowed these lines of code from http://www.bit.ly/174eqjy
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingString:#"upload.png"];
NSString *upLoad = [documentsDirectory stringByAppendingString:#"upload.png"];
NSData *myData = [[NSData alloc]initWithContentsOfFile:appFile];
//Here is the line that fails
[bailey addAttachmentData:myData mimeType:#"image/png" fileName:#"upload"];
//Up to here are the borrowed code lines.
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Facebook Account Detected" message:#"There are no Facebook Accounts Detected. You can configure them in Settings." delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[alert show];
}}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
And my code for my FirstViewController.h is
#import <UIKit/UIKit.h>
#import <Social/Social.h>
#interface FirstViewController : UIViewController {SLComposeViewController *slComposeViewController;
UIImage *upLoad;}
- (IBAction)ShareFB;
#end
My app is designed to Take a photo and display the photo (and it does that) and then save that image to the local documents folder on the app (which I got from another post) and then specify that image to upload to Facebook (which I have)
All that works except the saving to a local documents.
If you need to store file in documents directory, use like this,
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Images"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *imageFilePath = [NSString stringWithFormat:#"%#/%#",dataPath,#"upload.png"];
UIImage *image = [UIImage imageNamed:#"image"]; //Here place your image
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
[imageData writeToFile:imageFilePath atomically:YES];
If you need to attach image in facebook, use this statement,
[slComposeViewController
addAttachmentData:UIImagePNGRepresentation(image, 1) mimeType:#"image/png" fileName:#"upload.png"];
With the help of Karthika, and his facebook upload code, I was typing it in when I realised that I did not need to implement local documents saving.
Facebook let me add the image in without saving it.
Thanks though Karthika, I could not have done it without you.

pass url information in segue

I have 2 button set each with a segue to a view controller with a web view. I'm try to load a url in the web view based on which button started the segue.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString: #"toWeb"]){
NSString *abc = #"http://www.abc.com/";
NSURL *url = [NSURL URLWithString:kmb];
NetView *netview =[segue destinationViewController];
[netview.internet loadRequest:[NSURLRequest requestWithURL:url]];
}else if ([segue.identifier isEqualToString: #"toFacebook"]){
NSString *fb = #"http://www.facebook.com/ABC?ref=hl";
NSURL *url2 = [NSURL URLWithString:fb];
NetView *netview =[segue destinationViewController];
[netview.internet loadRequest:[NSURLRequest requestWithURL:url2]];
}
}
This is not working but I'm not getting any error just a bland view on the new screen. I'm not sure what the problem is. Can anyone help point me in the right direction? Thank You.
The problem is that the webview on the destination controller has not been loaded at this point. Just set a property on the destination controller to hold your url and then on its viewDidLoad method send the message to the webview in order to load the request. Something like this:
NetView.h
...
#property (nonatomic, copy) NSString *url;
NetView.m
...
#synthesize url;
Your code snippet:
if ([segue.identifier isEqualToString: #"toWeb"]){
NetView *netview = [segue destinationViewController];
netview.url = #"http://www.abc.com/";
}
...
NetView.m
- (void)viewDidLoad
{
NSURL *urlToLoad = [NSURL URLWithString:self.url];
[self.internet loadRequest:[NSURLRequest requestWithURL:urlToLoad]];
}

How to increase scroll speed of UIWebView?

I have an app that uses a UIWebView on one of it's tabs.
Everything is working like it should, but the speed that the view is scrolling is extremely slow! It doesn't matter if I build it in the simulator or if I build it in my iPhone, it's the same slow scroll.
How can I increase the scrolling speed of the view? I've noticed that it will stop scrolling as soon as the finger leaves the screen, instead of keep scrolling and decelerate like in safari, does this have anything to do with it?
The is my .h file:
// FirstViewController_SE.h
// WebApp
//
// Created by Camilla Fröberg on 2012-03-29.
// Copyright (c) 2012 SafeLine Sweden AB. All rights reserved.
//
#import <UIKit/UIKit.h>
#interface FirstViewController_SE : UIViewController<UIWebViewDelegate> {
IBOutlet UIWebView *webDisplay_SE;
UIBarButtonItem* mBack;
UINavigationItem* back;
}
#property(nonatomic,retain) UIWebView *webDisplay_SE;
#property (nonatomic, retain) IBOutlet UIBarButtonItem* back;
- (void)updateButtons;
#end
And this is my .m file:
//
// FirstViewController_SE.m
// WebApp
//
// Created by Camilla Fröberg on 2012-03-29.
// Copyright (c) 2012 SafeLine Sweden AB. All rights reserved.
//
#import "FirstViewController_SE.h"
#interface FirstViewController_SE ()
#end
#implementation FirstViewController_SE;
#synthesize webDisplay_SE;
#synthesize back = mBack;
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
self.webDisplay_SE.delegate = self;
NSString *urlAddress = #"http://www.safeline.eu/mobile/se/product";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webDisplay_SE loadRequest:requestObj];
[self updateButtons];
}
- (void)viewDidUnload {
self.back = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)updateButtons
{
self.back.enabled = self.webDisplay_SE.canGoBack;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (BOOL)webDisplay_SE:(UIWebView *)webDisplay_SE shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webDisplay_SE
{
[self updateButtons];
}
- (void)webViewDidFinishLoad:(UIWebView *)webDisplay_SE
{
[self updateButtons];
}
#end
Try this:
webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
Note: there's a bug in iOS 9 that you may need to workaround https://stackoverflow.com/a/32843700/308315

How do I load html into a webview?

I have just re-designed my iPhone app using Storyboard... questin is: how do I address the the UIWebView so I can load the html? (I am a newbie when it comes to Obj-C, having done my previous app in MonoTouch, so I'm kinda lost). :D
- (void)viewDidLoad {
NSString *urlAddress = #”http://www.stackoverflow.com”;
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
}
Apple Developer docs are really good resource. The usage of UIWebView is outlined here enter link description here
To load a network resource simply pass a NSURLRequest object to loadRequest.
[self.myWebView loadRequest:[NSURLRequest
requestWithURL:[NSURL URLWithString:#"http://www.apple.com/"]]];
You can also do this in viewDidLoad (a UIWebView is a subclass of UIView and inherits all its methods). For example, loading a local pdf resource.
- (void)viewDidLoad {
[super viewDidLoad];
NSString *thePath = [[NSBundle mainBundle] pathForResource:#"iPhone_User_Guide" ofType:#"pdf"];
if (thePath) {
NSData *pdfData = [NSData dataWithContentsOfFile:thePath];
[(UIWebView *)self.view loadData:pdfData MIMEType:#"application/pdf"
textEncodingName:#"utf-8" baseURL:nil];
}
}
To setup your UIWebView with a link, just use the following code.
var URLPath = "Insert email address here"
Then use...
loadAddressURL()
and finally...
func loadAddressURL(){
let requestURL = NSURL(string:URLPath)
let request = NSURLRequest(URL: requestURL!)
Webview.loadRequest(request)
}

Archiving and Unarchiving results in Bad Access

I'm having trouble setting up a model object to save the visual state of user generated CALayers in a simple graphics application for the iphone.
I'm attempting to save the background color and frame of all the current layers on screen by passing those properties to model objects which implement the NSCoding protocol and then into an NSMutableArray which the app delegate owns. Then I archive the array with NSKeyedArchiver and store it in the NSUserDefaults.
Each CALayer's backgroundColor property is converted to a UIColor to be encoded by the model object for storage. I think that I'm unarchiving the array incorrectly or not restoring state from the unarchived array correctly. When I attempt to access the UIColor object that was store in the model object, I get an EXC_BAD_ACCESS.
I thought it was possibly a bug with encoding UIColor objects so tried pulling the values out of the CGColorRef with the CGColorGetComponents function and storing them in an array to encode and archive, but I had the same result of bad access after unarchiving, so I think I'm just doing it wrong.
This is my model object:
#interface AILayerData : NSObject <NSCoding> {
UIColor* color;
CGRect frame;
}
#property (retain) UIColor* color;
#property (assign) CGRect frame;
#end
#implementation AILayerData
#synthesize color;
#synthesize frame;
- (void)encodeWithCoder:(NSCoder *)coder;
{
[coder encodeObject:color forKey:#"color"];
[coder encodeCGRect:frame forKey:#"frame"];
}
- (id)initWithCoder:(NSCoder *)coder;
{
self = [[AILayerData alloc] init];
if (self != nil)
{
color = [coder decodeObjectForKey:#"color"];
frame = [coder decodeCGRectForKey:#"frame"];
}
return self;
}
#end
And this is my archiving implementation:
#implementation AppDelegate
- (void)applicationWillTerminate:(UIApplication *)application {
NSArray *layersArray = viewController.view.layer.sublayers;
dataArray = [NSMutableArray array];
for(AILayer *layer in layersArray)
{
AILayerData *layerData = [[AILayerData alloc] init];
layerData.frame = layer.frame;
UIColor *layerColor = [UIColor colorWithCGColor:layer.backgroundColor];
layerData.color = layerColor;
[dataArray addObject:layerData];
[layerData release];
}
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:layerDataArray] forKey:#"savedArray"];
}
#end
And here is where I restore state:
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
spaceView = [[AISpaceView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.view = spaceView;
[spaceView release];
spaceView.delegate = self;
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:#"savedArray"];
if (dataRepresentingSavedArray != nil) {
[self restoreStateWithData:dataRepresentingSavedArray];
}
}
- (void)restoreStateWithData:(NSData *)data
{
NSArray *savedLayers = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if (savedLayers != nil) {
NSArray *restoredLayers = [[NSArray alloc] initWithArray:savedLayers];
for(AILayerData *layerDataObject in restoredLayers) {
UIColor *layerColor = layerDataObject.color;
AILayer *newLayer = [[AILayer alloc] init];
newLayer.backgroundColor = layerColor.CGColor;
newLayer.frame = layerDataObject.frame;
newLayer.isSelected = NO;
[self.view.layer addSublayer:newLayer];
[newLayer release];
}
[restoredLayers release];
[spaceView.layer layoutSublayers];
}
}
#end
Any help with this is greatly appreciated. I'm pretty much a noob. I was encoding, archiving and unarching an NSArray of NSNumbers converted from the color's floats in pretty much the same way and getting bad access.
You certainly want to retain the color in initWithCoder:
color = [[coder decodeObjectForKey:#"color"] retain];
or, with the dot syntax as color was declared as a retain property:
self.color = [coder decodeObjectForKey:#"color"];
You are over-releasing layerColor: You don't own it (layerDataObject does), but you are releasing it.
It looks like NSCoder for iPhone doesn't respond to -encodeWithCGRect:
Source: http://17.254.2.129/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSCoder_Class/Reference/NSCoder.html

Resources