Hi in my application I have image which change every day as per the date now i want to give download option for the user like they have to download by clicking button and they can see in there device. I'm searching for long time to achieve this task but not able get the proper solution please tell me how to achieve this one.
My ImageView code.
- (void)viewDidLoad
{
[super viewDidLoad];
//this is url which gives the date has a echo
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"url"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
// here I'm connecting the date to my url do display the image
NSString *imgstr=[NSString stringWithFormat:#"url",resSrt];
//assign your image view name
imageview.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",imgstr] ]]];
}
I have used the above to do display the image now to want to user download the image by clicking the download button to localstorage of the device please tell me how to achieve this.
Thanks.
First download the image synchronously and save it in documents folder, then show it over image view.
NSURL *url = [NSURL URLWithString: #"url"];
NSString *imagePath = [DOCUMENTS_PATH stringByAppendingPathComponent:#"some name"];
NSError *error = nil;
NSData *imageData = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error: &error];
if (!error) {
[imageData writeToFile:imagePath atomically:YES];
}
Then give this image to the image view
imageview.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/some name", DOCUMENTS_PATH]];
Related
I am trying to learn web service on iOS.
I'm starting of from getting an image from a JSON api link.
I've used the code below but the image is not displaying and I'm getting warning that says
Incompatible pointer types assigning to 'UIImage * _Nullable' from 'NSSting * _Nullable'
My code
NSURL *urlAdPop = [NSURL URLWithString:#"JSON LINK HERE"];
NSURLRequest *request = [NSURLRequest requestWithURL:urlAdPop];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *AdPopUp = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
popUpBanner.image = [[AdPopUp objectForKey:#"ad_image"] stringValue];
popUpAdURL = [AdPopUp objectForKey:#"ad_link"];
}
}];
popUpBanner.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:popUpAdURL]];
popUpBanner.hidden = NO;
popUpBanner.layer.cornerRadius = 9;
popUpBanner.clipsToBounds = YES;
popUpBanner.userInteractionEnabled = YES;
[self.view addSubview:popUpBanner];
You need to write your code inside block after you get response from webservice.
NSURL *urlAdPop = [NSURL URLWithString:#"JSON LINK HERE"];
NSURLRequest *request = [NSURLRequest requestWithURL:urlAdPop];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *AdPopUp = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
popUpBanner.image = [[AdPopUp objectForKey:#"ad_image"] stringValue];
popUpAdURL = [AdPopUp objectForKey:#"ad_link"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:popUpAdURL]];
dispatch_async(dispatch_get_main_queue(), ^{ // get main thread to update image
popUpBanner.image= image
popUpBanner.hidden = NO;
popUpBanner.layer.cornerRadius = 9;
popUpBanner.clipsToBounds = YES;
popUpBanner.userInteractionEnabled = YES;
[self.view addSubview:popUpBanner];
});
}
}];
popUpBanner.layer.cornerRadius = 9;
popUpBanner.clipsToBounds = YES;
popUpBanner.userInteractionEnabled = YES;
popUpBanner.hidden = YES;
[self.view addSubview:popUpBanner];
NSString* strURL=#"JSON LINK HERE";
NSString* webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *urlAdPop = [NSURL URLWithString:webStringURL];
NSURLRequest *request = [NSURLRequest requestWithURL:urlAdPop];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *AdPopUp = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
popUpAdURL = [AdPopUp objectForKey:#"ad_link"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[AdPopUp objectForKey:#"ad_image"]]]];
if (imgData)
{
UIImage *image = [UIImage imageWithData:imgData];
if (image)
{
dispatch_async(dispatch_get_main_queue(), ^{
popUpBanner.image = image;
popUpBanner.hidden = NO;
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
});
}
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
});
}
});
}
}];
Perfect way to display image!
Hope It will help you :)
If you need to deal with images comes from web response then you can use SDWebImage library from GitHub.
In its read me page they have also provided the way how you can achieve it.
#import <SDWebImage/UIImageView+WebCache.h>
[self.YourImageView sd_setImageWithURL:[NSURL URLWithString:#"http://yourimagePath/.../"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
Thats it !
Firstly,check if that url available in browser. If yes,check if your app accept HTTP(not HTTPS). You can set app accept like this:
You are adding popUpBanner in view after getting image from server. so you have to initialize it before in viewdidload and need to set it's frame.
Then set image to popUpBanner from completion handler of web service on main thread. And make sure that you have to set image not image name string!
Below line is wrong, it is trying to set string to imageview which is not possible.
popUpBanner.image = [[AdPopUp objectForKey:#"ad_image"] stringValue];
get image from image url provided by service side and use image name that you get in response.
And make sure that you are getting image object using breakpoint.
Hope this will help :)
###require suppurate api to load image.
want to attach the link and image name together as to reach. thus two strings are needed to store each the api and the image name.###
s=[[mutarray objectAtIndex:index]valueForKey:#"image"];
NSString *f=[NSString stringWithFormat:#"http://iroidtech.com/wecare/uploads/news_events/%#",s];
NSURL *g=[[NSURL alloc]initWithString:f];
data=[NSMutableData dataWithContentsOfURL:g];
self.imgvw.image=[UIImage imageWithData:data];
_descrilbl.text=[[mutarray objectAtIndex:index]valueForKey:#"image"];
I'm practicing how to parse XML data and store it into the sqlite. I have done parsing and storing successfully. But I have one problem with displaying image from an url. The URL is formed by combining two NSStrings. One for the fixed address(which I set value) and other based on the name of the photo(retrieved from Sqlite). I am able to create complete URL by retrieving name of photo from Sqlite. But strange thing happen when I use that URL to display image in UIImageView. It does not work. After some testing, I found out there is something wrong with the portion(photo name) I retrieved from Sqlite. If I combine the fixed address with literal name of the photo, it works. Can somebody explain why it happens like this. Thanks in advance.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"user.db"];
FMDatabase * database = [FMDatabase databaseWithPath:defaultDBPath];
[database open];
results=[database executeQuery:#"SELECT * FROM plant WHERE name=?",self.plantname];
while([results next]) {
name = [results stringForColumn:#"name"];
category = [results stringForColumn:#"category"];
instructions = [results stringForColumn:#"instructions"];
price = [results stringForColumn:#"price"];
photo=[results stringForColumn:#"photo"];
}
NSString * fixedURL = #"http://services.hanselandpetal.com/photos/";
NSString *url=[fixedURL stringByAppendingString:photo];
NSLog(url);
NSURL * imgURL = [NSURL URLWithString:url];
NSData * imageData = [NSData dataWithContentsOfURL:imgURL];
UIImage * image = [UIImage imageWithData:imageData];
self.plantImageView.image=image;
Edit
I've edited based on Rob answer. But there are still problems. I put log below. I've already tried to remove white spaces by using [photo stringByReplacingOccurrencesOfString:#" " withString:#""]. But it does not seem to affect.
2014-10-15 02:12:39.505 SqlitePractice[9256:286525] url string = 'http:/services.hanselandpetal.com/photos/mona_lavender.jpg'
2014-10-15 02:12:39.506 SqlitePractice[9256:286525] imgURL = (null)
2014-10-15 02:12:39.516 SqlitePractice[9256:286525] sendAsynchronousRequest failed: Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo=0x7a78ba50 {NSUnderlyingError=0x7a66b5e0 "unsupported URL", NSLocalizedDescription=unsupported URL}
Edit 2
The URL seems to be problem after changing from stringByAppendingString to stringByAppendingPathComponent. But I found out that even without one slash after http: , it works if I change the photo value. And the image is displayed.
NSString * fixedURL = #"http://services.hanselandpetal.com/photos/";
photo=#"bougainvillea.jpg";
NSString *url=[fixedURL stringByAppendingPathComponent:photo];
NSLog(#"url string = '%#'", url);
NSURL * imgURL = [NSURL URLWithString:url];
NSLog(#"imgURL = %#", imgURL);
And the log is below,
2014-10-15 12:07:56.650 SqlitePractice[9690:308022] url string = 'http:/services.hanselandpetal.com/photos/bougainvillea.jpg'
2014-10-15 12:07:56.651 SqlitePractice[9690:308022] imgURL = http:/services.hanselandpetal.com/photos/bougainvillea.jpg
Edit 3
I have changed based on Rob's modified answer.
NSURL *fixedURL = [NSURL URLWithString:#"http://services.hanselandpetal.com/photos/"];
NSURL *url = [fixedURL URLByAppendingPathComponent:[photo stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"image URL = '%#'", url);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"sendAsynchronousRequest failed: %#", error);
return;
}
UIImage *image = [UIImage imageWithData:data];
self.plantImageView.image=image;
}];
And here is the log message:
2014-10-15 13:40:38.977 SqlitePractice[10436:357359] image URL = 'http://services.hanselandpetal.com/photos/camellia.jpg%250A%2520%2520%2520%2520'
A couple of thoughts:
Unrelated to your problem at hand, instead of stringByAppendingString, it's generally better to use URLByAppendingPathComponent with a NSURL. It takes care of adding any necessary / characters for you. Not critical given your example, but it's more robust.
Also, if the string might have spaces or other characters not permitted in a URL, you might percent escape it, too.
Thus, you'd do something like:
NSURL *fixedURL = [NSURL URLWithString:#"http://services.hanselandpetal.com/photos/"];
NSURL *url = [fixedURL URLByAppendingPathComponent:[photo stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
You should NSLog the NSURL variable and make sure it's not nil (e.g. which could be caused if there were some spaces in the photo string, for example, unless you percent escape it).
In your revised question, in which you share the log, the original URL string (before the conversion to the NSURL) is being reported as:
http:/services.hanselandpetal.com/photos/mona_lavender.jpg
That should be:
http://services.hanselandpetal.com/photos/mona_lavender.jpg
If imgURL is not nil, but imageData is, you might want to retrieve the image data in a manner that retrieves the error. For example, you could:
NSError *error = nil;
NSData *imageData = [NSData dataWithContentsOfURL:imgURL options:0 error:&error];
if (!imageData) {
NSLog(#"dataWithContentsOfURL failed: %#", error);
}
Bottom line, go through this one line at a time and identify precisely where it is going wrong.
As an aside, you generally would want to avoid using dataWithContentsOfURL, but instead use an asynchronous method:
NSURL *fixedURL = [NSURL URLWithString:#"http://services.hanselandpetal.com/photos/"];
NSURL *url = [fixedURL URLByAppendingPathComponent:[photo stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NRURLRequest *request = [NSURLRequest requestWithURL:imgURL];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"sendAsynchronousRequest failed: %#", error);
return;
}
UIImage *image = [UIImage imageWithData:data];
self.plantImageView.image=image;
}];
I belive that UIIMAGEVIEW will not display Url as image path. I would sugest to try with UIWebView which would display web content (image or whole web page). This example is writen in objective-c.
self.myWebView = [[UIWebView alloc] initWithFrame:self.view.bounds];
self.myWebView.scalesPageToFit = YES ;
[self.view addSubview:self.myWebView];
NSURL *url = [NSURL URLWithString:#"http://services.hanselandpetal.com/photos/mona_lavender.jpg"];
NSURLRequest *request = [ NSURLRequest requestWithURL:url];
[self.myWebView loadRequest:request]
I have some code that gets an image from a web page and displays it in an ImageView. But the image loads very slowly for some reason I don't really understand! Through my logging I can see that all the data for the image (base64 string) arrives pretty instantly, yet it takes about 12 - 15 seconds for the image to appear in the ImageView.
I find this very strange because I used an NSStream to get the data for the image in a different method and the image loaded as soon as all the data arrived. But with this URLSession method its taking longer for the image to load. This doesn't really make sense! This method shouldn't affect how the ImageView loads that data.
Has anybody any ideas why this might be happening?
heres the code:
- (void)postMethod:(NSDictionary *)numDict
{
NSURL *url = [NSURL URLWithString:#"http://theWebAddress.com/aPage.php"]; // add url to page
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:numDict options:kNilOptions error:&error];
NSLog(#"%#", numDict);
if (!error)
{
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
for (id key in diction)
{
if ([key isEqualToString:#"text"])
{
NSLog(#"data is text");
self.messageLabel.text = diction[#"text"];
break;
}
else if ([key isEqualToString:#"image"])
{
NSLog(#"data is an image");
// gets the base64 string pretty instantly but takes 12 - 15 seconds to pop up in the imageView
NSData *ImgData = [[NSData alloc] init];
ImgData = [[NSData alloc] initWithBase64EncodedString:diction[#"image"] options:1];
self.ImageView.image = [UIImage imageWithData:ImgData];
break;
}
}
}];
[uploadTask resume];
}
}
many thanks!
Your completion handler might be operating on a background thread. UI updates should always work on the main thread. Put a break point at
self.ImageView.image = [UIImage imageWithData:ImgData];
and see if it is on the main thread. If not, dispatch it to the main thread before you set the ImageView.image:
dispatch_async(dispatch_get_main_queue(), ^{
self.ImageView.image = [UIImage imageWithData:ImgData];
});
You can try to use SDWebImage https://github.com/rs/SDWebImage and all you need is to set the image in imageView like this:
[cell.imageView setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
You are firstly downloading image and then showing image.You can download image by using lazy loading.
For this you can use EgoImageView not uiimageview.
self.ImageView.imageURL=[NSURL URLWithString:
here self.ImageView is of egoimageview type.
you can get this class from github.
https://github.com/enormego/EGOImageLoading
After login to the salesforce in my app I am making service call which returns the list of products with attributes like productName and product image url.
I am trying to download the image from product image url in this way
SFOAuthCredentials *credentials =[SFAccountManager sharedInstance].credentials;
NSString *urlString = [NSString stringWithFormat:#"%#?oauth_token=%#",imageUrl,credentials.accessToken];
NSURL *imgUrl = [[NSURL alloc] initWithString:[URLString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSURLRequest *imgRequest=[[NSURLRequest alloc]initWithURL:imgUrl];
[NSURLConnection sendAsynchronousRequest:imgRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
UIImage *image=[[UIImage alloc] initWithData:data];
NSLog(#"Image Object %#",image);
}];
I am getting the data object of size around 1820 bytes, but while converting NSData to UIImage by using UIImage classsMethod [UIImage iamgeWithData:data] or instance method [UIImage alloc] initWithData:data] I am getting null
Can anyone help me to fix this issue?.
How to tell if the NSData returns nil if theres no internet connection or if the image is no longer available ??
this is the code:
NSString *str = #"http://p.twimg.com/A76-I-PCYAA75YH.jpg";//URL is broken
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
image = [UIImage imageWithData:imgData];
The nsdata is nil in two cases:
If thers no internet connection.
Or if the image in the url is no longer available.
Try this code.
NSURL* url = [NSURL URLWithString:#"http://imageAddress.com"];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
NSImage* image = [[NSImage alloc] initWithData:data];
// do whatever you want with image
}
}];
You should first test for an available network data connection separately, see Apple's Reachability sample code.
Then, if you have a network connection, you can go ahead and try and load the file. If it then fails, you know it's not because there was no network data connection.
Before downloading check for internet connection and then download. You can check availaibility bu putting condition of
if(imgdata == nil)
// image is not available in server
else
// convert data into image and use
image = [UIImage imageWithData:imgData];