During start up, how can load remote image? - objective-c

I success to load the image and JSON with NSURLSession.
But I want to load these files during Start up.(When launchImage is viewed, file is loaded and launchImage is disappeared then remote-image is shown up) How can I do this?

Although yes, a library is not always necessary, I do find AFNetworking to be very handy in this case. Import AFNetworking.h and UIImageView+AFNetworking.h and you can make requests like this for images from a remote server. After creating an imageView you can load the image into a UIImageView using a request like this.
[imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://image.url"]]
placeholderImage:[UIImage imageNamed:#"loading"]
success:^(NSURLRequest *request , NSHTTPURLResponse *response , UIImage *image ){
NSLog(#"Loaded successfully: %d", [response statusCode]);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
NSLog(#"failed loading: %#", error);
}
];
Using the NSHTTPURLResponse you can also get the image and do whatever caching you would like or save it to a directory.
Edit: This question was phrased in a way difficult to understand. Although this may not directly answer the askers question, it is relevant to the question's title and could help someone who searches for it in the future.

Related

How to implement lazy loading of image without using SDImageCache?

How to implement lazy loading of image without using below link:
https://github.com/rs/SDWebImage
Note: I don't want to use any third party tool. I want to do from my side.
If you don't want to use any library (some are MIT or public domain licensed, so I think the only reason not to use them is that you want to learn how to build it yourself).
Here is how to do it with a simple and effective way:
1 : Put a temporary placeholder image in your imageView.
2 : Get your image in background thread.
2-a : If you want the cache feature, search for a cached image.
2-b : If no cache feature or no cached image, get your image from its source.
2-c : If cache feature, save the image to cache.
3 : In main thread show your image in the imageView.
Pseudo Code : (I wrote it on the go, it is not meant to run and it may have errors, sorry for that).
-(void) lazilyLoadImageFromURL :(NSURL *)url{
imageView.image = [UIImage imageNamed:#"Placeholder.png];
if([self cachedImageAvailableForURL:url){
imageView.image= [self cachedImageForURL:url];
}
else{
NSOperationQueue *queue = [NSOperationQueue mainQueue];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse * resp, NSData *data, NSError *error)
{
dispatch_async(dispatch_get_main_queue(),^
{
if ( error == nil && data )
{
UIImage *urlImage = [[UIImage alloc] initWithData:data];
imageView.image = urlImage;
[self saveImageInCache:image forURL:url];
}
});
}];
}
}
-(BOOL) cachedImageAvailableForURL:(NSURL*):url{
// check if there is a saved cached image for this url
}
-(UIImage *) cachedImageForURL:(NSURL*):url{
// returns the cached image for that url
}
-(void) saveImageInCache:(UIImage*) image forURL:(NSURL*)url{
// saves the image in cache for the url
}
Of course, this is only ONE POSSIBLE WAY to do it. I tried to make it simple, but there are plenty better and more complicated ways to do it.
Try it:
NSURL *imageURL = [NSURL URLWithString:#"www...."];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
self.imgVWprofile.image=[UIImage imageWithData:imageData];
});
});

Unable to download and view images from parse in iOS

As of yesterday I was able to view images fine but now I can't view from url and get error as
NSErrorFailingURLKey=http://files.parsetfss.com
Some images are working fine while others are getting issues.
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:objStampData.stampImage.url] placeholderImage:[UIImage imageNamed:#"PlaceHolder.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
{
if(!error)
{
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
}
else
{
NSLog(#"Error %#",error);
}
}];
Two possible reasons:
Name of the image in parse. There I have problem when the name contains somestrange symbols like ".","&" and etc. Try with simple name and different image format.
Check if you allow
access to parse from the plist file check here

Images from url in UITableViewCell loads only when i scroll the table view

Images downloaded from url displays image in UITableViewCell only when i start scrolling the UITableView. Now i am using following code to load image from url:
NSURL* url = [NSURL URLWithString:imageURL];
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
}
}];
Thanks in advance.
You shouldn't be getting your images in - (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath you should create a utility class that acts as backing datastore. As you code stands now you could conceivable be re-requesting the image multiple times as the cell is scrolled into and out of view.
I Strongly recommend SDWebImage, which is very simple and powerful.
You can use setImageWithURL category , simply set image for imageView. For example
[cell.imageView setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];`
And you can simply save your image cache by [[SDImageCache sharedImageCache] storeImage:myImage forKey:myImageCacheKey] and simply query your image cache by [[SDImageCache sharedImageCache] queryDiskCacheForKey:myImageCacheKey done:^doneBlock];
Very simple and powerful, for more details checkout the here SDWebImage;

AFNetworking JSON parsing - fails of unknown reason

im trying to parse some JSON. for simplicity ill explain using the default example at github:
when running:
NSURL *url = [NSURL URLWithString:#"http://httpbin.org/ip"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request success:^(
NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"IP Address: %#", [JSON valueForKeyPath:#"origin"]);
} failure:nil];
[operation start];
i get the correct output logged. however, when i copy the example's content (which is basically 1 element) to a txt or html file (so URLWithString gets #"http:// my server address /file.txt"), putting it on my testing server and trying to prase from there, i get no output. what is wrong with this? thanks for your time!
(note: if i go to http:// my server address /file.txt i can see the contents there clearly so that's not the problem)
edit: as suggested, the content is:
"{
"origin": "10.44.119.100"
}"
Your problem probably has something to do with the fact that you're serving content as a text file (.txt) rather than as JSON (Content-Type: application.json / .json extension). AFNetworking is strict about HTTP standards in order to guard against unexpected behavior. Either set the correct Content-Type header on your server, or (as a hack) do AFJSONRequestOperation +addAcceptableContentTypes: adding text/plain.
As a meta note: when asking a question on Stack Overflow, specifics matter. If you had posted the error you were seeing in the console, it would be much easier to determine what the problem was. Likewise, approximate code is not actual code; if you have a problem, be specific about exactly what's going on. Details matter.
You should encode the json data first and then write it into the text file and when you are reading the data from file... decode the data first...
EDIT:
replace JSON operation with simple http and check if you are able to get data from there...
and if you are then JSONOperation basically is seeking for json response which is not in text file... i guess
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
[operation setUploadProgressBlock:^(NSInteger bytesWritten,long long totalBytesWritten,long long totalBytesExpectedToWrite)
{
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#" Success %#",str);
// id response = AFJSONDecode(responseObject, nil);
[self requestSucceed:response];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"error: %#", operation.responseString);
}];

Xcode: Validate a URL before Loading it

Im having some trouble findig a way to validate a url on my app.
My intention is to load a URL and at the same time see if other webpage exist for example.
Load http://mysite.com/folder1/1.pdf
validate http://mysite.com/folder1/2.pdf
if folder1/2.pdf exists then load it, else validate /folder2/1.pdf
so far im loading the first pdf like this in order to be able to change the pdf number and the folder:
int numpag = 1;
NSString *baseUrl =#"http://www.cronica.com.mx/iphone/pdf_iphone/";
[pdfView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[baseUrl stringByAppendingFormat:#"folder1/%d.pdf", numpag]]]];
Thanks so much in advance!
how about this:
+ (BOOL)isValidURL:(NSURL*)url
{
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSHTTPURLResponse *res = nil;
NSError *err = nil;
[NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&err];
return err!=nil && [res statusCode]!=404;
}
let me know if it works for you!
(keep in mind that this is a synchronous request and should not be executed on the main thread)
I had to change the line:
return err!=nil && [res statusCode]!=404;
to
return err==nil && [res statusCode]!=404;
for the correct Bool return. The error should remain nil.
This approach is NOT correct, You should avoid Synchronous calls as they are blocking.
Apple says: simply try and wait down to wait for response.