Load various images at same time from the internet objective-c - objective-c

I'm trying to load 5 images at the same time,for them put it on the view and change the image every 5 sec(change between the current 5)
I create the current a class wich is called when the viewdidload and starts the timer,the method to load all images is this:
-(NSMutableArray *)getAllPhotos
{
NSMutableArray * photosArray = [[NSMutableArray alloc]init];
NSString * pic0 = [NSString stringWithFormat:#"http://74.53.32.202/~ltashiro/public/Servidor/Images/0.png"];
NSString * pic1 = [NSString stringWithFormat:#"http://74.53.32.202/~ltashiro/public/Servidor/Images/1.png"];
NSString * pic2 = [NSString stringWithFormat:#"http://74.53.32.202/~ltashiro/public/Servidor/Images/2.png"];
NSString * pic3 = [NSString stringWithFormat:#"http://74.53.32.202/~ltashiro/public/Servidor/Images/3.png"];
NSURL *image0 = [NSURL URLWithString:pic0];
NSURL * image1 = [NSURL URLWithString:pic1];
NSURL * image2 = [NSURL URLWithString:pic2];
NSURL * image3 = [NSURL URLWithString:pic3];
NSMutableArray * arrayURL = [[NSMutableArray alloc]init];
[arrayURL addObject:image0];
[arrayURL addObject:image1];
[arrayURL addObject:image2];
[arrayURL addObject:image3];
for (int i = 0; i<4; i++)
{
NSData * imageData = [[NSData alloc]initWithContentsOfURL:[arrayURL objectAtIndex:i]];
Photo * aPhoto = [[Photo alloc]init];
aPhoto.photoID = (i+1);
aPhoto.photo = [[UIImage alloc]initWithData:imageData];
[photosArray addObject:aPhoto];
[aPhoto release];
[imageData release];
}
return photosArray;
}
But sometimes the appcrashs on launch,theres any other solution abordation to it?

I was searching for the problem posted here. I found a solution here:
http://www.switchonthecode.com/tutorials/loading-images-asynchronously-on-iphone-using-nsinvocationoperation
Didn't test it yet though.

Related

How to reload data into NSTableView?

I am fairly new to Objective-C and I find there are a lot of tutorials for iOS and UITableView but almost none for OS X Apps via NSTableView. I have built a method to retrieve my data but I get an error on the last line:
"Property tableView not found on object type ProductsViewController".
I do not know the correct way to reload my data into my table or if I even need to use an NSTableView for this specific instance? Is there a better way to display my data than using NSTableView?
#import "ProductsViewController.h"
#import "Product.h"
#define getDataURL #"http://myurl"
#interface ProductsViewController ()
#end
#implementation ProductsViewController
#synthesize jsonArray, productsArray;
- (void)viewDidLoad {
[super viewDidLoad];
[self retrieveData];
}
-(NSInteger)numberOfRowsInTable:(NSTableView *)tableView{
return productsArray.count;
}
- (void) retrieveData{
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
productsArray = [[NSMutableArray alloc] init];
for(int i = 0; i < jsonArray.count; i++){
NSString * pID = [[jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString * pName = [[jsonArray objectAtIndex:i] objectForKey:#"product_name"];
NSString * pPrice = [[jsonArray objectAtIndex:i] objectForKey:#"product_price"];
NSString * pDescription = [[jsonArray objectAtIndex:i] objectForKey:#"product_description"];
NSString * pImage = [[jsonArray objectAtIndex:i] objectForKey:#"product_image"];
NSString * pDownload = [[jsonArray objectAtIndex:i] objectForKey:#"product_download"];
NSString * pVideo = [[jsonArray objectAtIndex:i] objectForKey:#"product_video"];
NSString * pFeatured = [[jsonArray objectAtIndex:i] objectForKey:#"featured"];
[productsArray addObject:[[Product alloc] initWithProduct_Name: pName andProduct_Price:pPrice andProduct_Description:pDescription andProduct_Image:pImage andProduct_Download:pDownload andProduct_Video:pVideo andProduct_Featured:pFeatured andProduct_ID:pID]];
}
[self.tableView reloadData];
}
You need to implement the required delegate methods for the NSTableViewDataSource protocol. Specifically, you need these two:
numberOfRowsInTableView:
tableView:objectValueForTableColumn:row:
The table view will then call these methods for the data it wants.
In addition, there's a great tutorial over at raywenderlich.com about using NSTableViews.

Get all Images from Live Photo

I want to get a NSArray with all the UIImage from a Live Photo to create a GIF of that. I tried to make screenshots while animating the live photo but it doesn't work.
Can anyone help me?
Thanks!
First step, you need convert a Live Photo to Video, using this:
PHAssetResourceManager.defaultManager().writeDataForAssetResource(assetRes,
toFile: fileURL, options: nil, completionHandler:
{
// Video file has been written to path specified via fileURL
}
Finally, using this library to convert this to GIF, or you can search in google for another way: https://github.com/NSRare/NSGIF
Hope this will help you.
This is what I did to achieve the same thing as you requested.
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:NO]];
options.predicate = [NSPredicate predicateWithFormat:#"mediaType == %d", PHAssetMediaTypeImage];
options.predicate = [NSPredicate predicateWithFormat:#"mediaSubtype == %d", PHAssetMediaSubtypePhotoLive];
options.includeAllBurstAssets = NO;
PHFetchResult *allLivePhotos = [PHAsset fetchAssetsWithOptions:options];
NSLog(#"Get total live count : %ld",(unsigned long)allLivePhotos.count);
NSMutableArray *arrAllLiveImagesGroups = [NSMutableArray array];
for (PHAsset *asset in allLivePhotos) {
[asset requestContentEditingInputWithOptions:nil
completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {
NSURL *urlMov = [contentEditingInput.livePhoto valueForKey:#"videoURL"];
NSMutableArray *arrLive = [NSMutableArray array];
NSMutableArray *arrSingleLiveImagesGroup = [NSMutableArray array];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:urlMov options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.requestedTimeToleranceAfter = kCMTimeZero;
generator.requestedTimeToleranceBefore = kCMTimeZero;
for (Float64 i = 0; i < CMTimeGetSeconds(asset.duration) * 5 ; i++){
#autoreleasepool {
CMTime time = CMTimeMake(i, 5);
NSError *err;
CMTime actualTime;
CGImageRef image = [generator copyCGImageAtTime:time actualTime:&actualTime error:&err];
UIImage *generatedImage = [[UIImage alloc] initWithCGImage:image scale:1.0 orientation:UIImageOrientationDown];
[arrLive addObject:generatedImage];
CGImageRelease(image);
}
}
[arrSingleLiveImagesGroup addObject:arrLive];
[arrAllLiveImagesGroups addObject:arrSingleLiveImagesGroup];
}];
}

Loading image from url ios 8 objective c

i´m trying to obtain the imagen from this url[#"file:///var/mobile/Media/DCIM/100APPLE/IMG_0158.JPG"], but i can´t.
Always is nil.
this is my code:
NSData *data = [NSData dataWithContentsOfURL: #"file:///var/mobile/Media/DCIM/100APPLE/IMG_0158.JPG"];
UIImage *image = [UIImage imageWithData:data];
self.pruebaTmp.image = image;
i obtain the url with this code:
if (asset) {
// get photo info from this asset
PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
imageRequestOptions.synchronous = YES;
[[PHImageManager defaultManager]
requestImageDataForAsset:asset
options:imageRequestOptions
resultHandler:^(NSData *imageData, NSString *dataUTI,
UIImageOrientation orientation,
NSDictionary *info)
{
NSURL *path = [info objectForKey:#"PHImageFileURLKey"];
//asignamos el path de la imágen seleccionada en galeria
self.pathImagen = path;
}];
}
if someone could help i would be very grateful, because i can´t load the image with the url obtained.
you can`t not get UIimage or metadata from that url.
you can get UIImage from local Identifier of access
PHFetchResult *savedAssets = [PHAsset fetchAssetsWithLocalIdentifiers:#[localIdentifier] options:nil];
[savedAssets enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
//this gets called for every asset from its localIdentifier you saved
//PHImageRequestOptionsDeliveryModeHighQualityFormat
PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
imageRequestOptions.synchronous = NO;
imageRequestOptions.deliveryMode = PHImageRequestOptionsResizeModeFast;
imageRequestOptions.resizeMode = PHImageRequestOptionsResizeModeFast;
[[PHImageManager defaultManager]requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFill options:imageRequestOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
NSLog(#"get image from result");
if (result) {
}
}];
imageRequestOptions = nil;
}];

How to parse a json file with /n and br line breaks in iPhone?

I am currently parsing a json file from a web server which was generated using a php son generator.But now the json file has /n and br tags in the content and when i parse the file,the app displays the /n and br tags.
Heres my code:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
static NSString *cellIdentifier=#"identity";
CustomCell2 *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.loader.hidden = NO;
[loader startAnimating];
[[NSBundle mainBundle]loadNibNamed:#"CustomCell11" owner:self options:nil];
cell=(CustomCell2 *)tblCell;
NSMutableArray *dictionaryObject=[_newsArray objectAtIndex:indexPath.row];
lblMain.text=[dictionaryObject valueForKey:#"MainHeadline"];
lblSummary.text=[dictionaryObject valueForKey:#"Story"];
lblEdition.text=[dictionaryObject valueForKey:#"Edition"];
//lblStory.text=[dictionaryObject valueForKey:#"FullStory"];
lblDate.text=[dictionaryObject valueForKey:#"PublishDate"];
lblAuthor.text=[dictionaryObject valueForKey:#"Author"];
dispatch_queue_t queue= dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSURL* url = [NSURL URLWithString:[dictionaryObject valueForKey:#"ImagePath"]];
NSData *data = [NSData dataWithContentsOfURL:url];
dispatch_sync(dispatch_get_main_queue(), ^{
UIImageView *imgViewThumb=[[UIImageView alloc]initWithFrame:imgView.frame];
[imgViewThumb setImage:[UIImage imageWithData:data]];
dispatch_async(dispatch_get_main_queue(), ^{
//cell image added below dispath..patching,il change this later..brrrrrr!!
[cell addSubview:imgViewThumb];
//cell.ImagePath.UIImage = imgViewThumb;
});
// [cell addSubview:imgViewThumb];
});
});
//what the heck???
return cell;
}
#pragma mark -methods
-(void)retrieveData{
NSURL * url =[NSURL URLWithString:getDataURL];
NSData *data =[NSData dataWithContentsOfURL:url];
_json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
_newsArray = [[NSMutableArray alloc]init];
for (int i = 0; i < _json.count; i++){
{
NSString * cID =[[_json objectAtIndex:i]objectForKey:#"ID"];
NSString * cName = [[_json objectAtIndex:i]objectForKey:#"MainHeadline"];
NSString * cState =[[_json objectAtIndex:i]objectForKey:#"FullStory"];
NSString * cPopulation =[[_json objectAtIndex:i]objectForKey:#"Edition"];
NSString * cCountry =[[_json objectAtIndex:i]objectForKey:#"PublishDate"];
NSString * cStory =[[_json objectAtIndex:i]objectForKey:#"Story"];
NSString * cAuthor =[[_json objectAtIndex:i]objectForKey:#"Author"];
UIImage *cImage =[[_json objectAtIndex:i]objectForKey:#"ImagePath"];
UIImage *cLogo =[[_json objectAtIndex:i]objectForKey:#"Logo"];
CustomCell2 *myCity = [[CustomCell2 alloc]initWithCityID:cID andCityName:cName andCityState:cState andCityPopulation:cPopulation andCityCountry:cCountry andStory:cStory andImagePath:cImage andAuthor:cAuthor andLogo:cLogo];
[_newsArray addObject:myCity];``
}
//[self.tblView reloadData];
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:#"detailView" sender:self];
}
#pragma mark - SlideNavigationController Methods -
- (BOOL)slideNavigationControllerShouldDisplayLeftMenu
{
return YES;
}
An example of better simpler code (in an answer for formatting):
// Current
for (int i = 0; i < _json.count; i++){
{
NSString * cID =[[_json objectAtIndex:i]objectForKey:#"ID"];
NSString * cName = [[_json objectAtIndex:i]objectForKey:#"MainHeadline"];
NSString * cState =[[_json objectAtIndex:i]objectForKey:#"FullStory"];
...
// Simplified
for (NSDictionary *item in _json) {
NSString * cID = item[#"ID"];
NSString * cName = item[#"MainHeadline"];
NSString * cState =item[#"FullStory"];
...
Studying the language documentation can payoff in simpler and clear code.
Also elimination of duplication can reduce simple errors.

Displaying images in tableview

I didnt get any images displayed, only the filename is shown.
Currently im using this codes:
NSString *filePath = [[self documentsPath] stringByAppendingPathComponent:#""];
NSFileManager *imagesFileManager = [NSFileManager defaultManager];
imagesArr = [[imagesFileManager contentsOfDirectoryAtPath:filePath error:nil]filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self ENDSWITH '.jpg'"]];
arryList = [[NSMutableArray alloc] initWithArray:[imagesArr copy]];//display text
imagesList = [[NSMutableArray alloc]init];//display image
for (NSString *anImage in arryList) {
anImage = [NSString stringWithFormat:#"Documents/%#",anImage];
[imagesList addObject:anImage];
}
In the for loop , you are just adding the file path to the array instead of UIImage.
Change the for loop as follows:
NSString *docPath = [self documentsPath];
for (NSString *anImagePath in arryList) {
anImagePath = [NSString stringWithFormat:#"%#/%#",docPath,anImagePath];
UIImage *image = [UIImage imageWithContentsOfFile:anImagePath];
if ( image )
[imagesList addObject:image];
}