UICollection View images from url - objective-c

I have followed this tutorial to make a UICollectionView custom layout: http://skeuo.com/uicollectionview-custom-layout-tutorial#section4
I got through it and I got it working. But when I try to use it with my own pictures I cannot get them show in the app.
Here's the code to get the pictures
self.albums = [NSMutableArray array];
NSURL *urlPrefix =
[NSURL URLWithString:#"https://raw.github.com/ShadoFlameX/PhotoCollectionView/master/Photos/"];
NSInteger photoIndex = 0;
for (NSInteger a = 0; a < 12; a++) {
BHAlbum *album = [[BHAlbum alloc] init];
album.name = [NSString stringWithFormat:#"Photo Album %d",a + 1];
NSUInteger photoCount = 1;
for (NSInteger p = 0; p < photoCount; p++) {
// there are up to 25 photos available to load from the code repository
NSString *photoFilename = [NSString stringWithFormat:#"thumbnail%d.jpg",photoIndex % 25];
NSURL *photoURL = [urlPrefix URLByAppendingPathComponent:photoFilename];
BHPhoto *photo = [BHPhoto photoWithImageURL:photoURL];
[album addPhoto:photo];
photoIndex++;
}
[self.albums addObject:album];
}
So the problem comes when I change the url string to the one with my pictures. I want to use a public website for hosting images like Flickr, but I also tried Imageshak.us and postimage.org and it didn't work.
I have the photo names as it says the string: thumbnail%d.jpd so that is not the problem. Any ideas?
UPDATE:
I tried using this
[NSURL URLWithString:#"http://www.flickr.com/photos/93436974#N06/"];
That's the url to the gallery, but it doesn't show anything. If I can't use Flickr, is there any other websites similar that could be used?

For your thumbnails you're naming them "thumbnail0.jpg" "thumbnail1.jpg" etc right? The %d means insert the number from outside the quotes here, for the code you posted it takes whichever number photo you're on and adds it into your string (up to a maximum of 25 at which point it will restart , ie photo 27 would return thumbnail2.jpg
Just quickly googling it looks like flickr doesn't keep the source file name so it wouldn't work with the code you posted. I would recommend photobucket I beilieve they keep the source file name and urls are easy to work with

Related

PHPhotoLibrary getting album and photo info

I am trying to get info on all the albums/photos using the PHPhotoLibrary. I barely know objective C, and i've looked at some tutorial/sample but couldn't find everything that I needed.
Here is a link to the sample code I based my code on.
https://developer.apple.com/library/ios/samplecode/UsingPhotosFramework/Introduction/Intro.html#//apple_ref/doc/uid/TP40014575-Intro-DontLinkElementID_2
So far I was able to get the albums name and identifier. And I am getting a list of photos, I am able to get their identifier as well, but not the filename. But if I put a break point in my fonction and look at my PHAsset pointer values, I can see the filename there (inside _filename), but if I try to call the variable with the filename in it, the variable does not exist.
So if anyone can provide a sample code to get all info on albums/photos/thumbnail that would be awesome. Or just getting the filename would be a good help.
Here is the code I have tried so far:
-(void)awakeFromNib{
NSMutableArray *allPhotos = self.getAllPhotos;
for (int x = 0; x < allPhotos.count; x ++)
{
PHAsset *photo = [self getPhotoAtIndex:x];
PHAssetSourceType source = photo.sourceType;
NSString *id = photo.localIdentifier;
NSString *description = photo.description;
NSUInteger height = photo.pixelHeight;
NSUInteger width = photo.pixelWidth;
NSLog(#"Test photo info");
}
}
-(PHAsset*) getPhotoAtIndex:(NSInteger) index
{
return [self.getAllPhotos objectAtIndex:index];
}
-(NSMutableArray *) getAllPhotos
{
NSMutableArray *photos = [[NSMutableArray alloc] init];
PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
allPhotosOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *allPhotos = [PHAsset fetchAssetsWithOptions:allPhotosOptions];
PHFetchResult *fetchResult = #[allPhotos][0];
for (int x = 0; x < fetchResult.count; x ++) {
PHAsset *asset = fetchResult[x];
photos[x] = asset;
}
return photos;
}
As you can see, I can get the image height and width, its id, but cannot get the url to it.
I have found a way to get the url of my photo.
-(void)getImageURL:(PHAsset*) asset
{
PHContentEditingInputRequestOptions *options = [[PHContentEditingInputRequestOptions alloc] init];
[options setCanHandleAdjustmentData:^BOOL(PHAdjustmentData *adjustmentData) {
return [adjustmentData.formatIdentifier isEqualToString:AdjustmentFormatIdentifier] && [adjustmentData.formatVersion isEqualToString:#"1.0"];
}];
[asset requestContentEditingInputWithOptions:options completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info)
{
NSURL* url = contentEditingInput.fullSizeImageURL;
}];
}
Filenames in the Photos library are an implementation detail and subject to change. There are various private API for discovering them (or ways to use valueForKey or other public introspection APIs to find where they're hidden), they aren't something to be relied upon. In particular, an asset that's been edited is likely to have a different filename than the original.
What do you need a filename/URL for? If you're just uniquely identifying the asset across launches of your app, use localIdentifier. If you're showing it to the user... why? Something like IMG_0234.jpg vs IMG_5672.jpg has little meaning to the average user.
To fetch the assets in a specific album, use fetchAssetsInAssetCollection:options:. To fetch the album(s) containing a specific asset, use fetchAssetCollectionsContainingAsset:withType:options:. To discover the list(s) of albums, use other APIs on PHAssetCollection and its superclass PHCollection.

Making a simple quiz game. Stuck with the arrays part

I'm trying to make a game with 2 views, the first view has buttons which segues to another view. Depending on the segue identifier, it loads an image which the player has to guess.
I also have a an array which lists hints for the 4 images.
With the array, i made a button which shows the hints on the view, but the problem I have right now is that I don't know how to set the correct array to the image/puzzle.
A code that works right now is this:
if ([self.thePuzzle.name isEqual: #"lion"])
{
NSArray *hints = [lines[0] componentsSeparatedByString:#" "];
self.hintLabel.text = hints[0];
}
But after adding another line for the second image/puzzle, the app crashes.
2nd UPDATE: code that crashes
After entering this code
if ([self.thePuzzle.name isEqual: #"penguin"])
{
NSArray *hints = [lines[1] componentsSeparatedByString:#" "];
self.hintLabel.text = hints[1];
}
The hint button works for the 1st code, which has the lion picture, while the second part of the code, for the penguin pic, crashes when the Hint button is pressed.
3rd Update: Additional information
I made xcode access a file from the internet which contained the words for my array.
This is how i coded it.
[super viewDidLoad];
// Do any additional setup after loading the view.
self.imageView.image = [UIImage imageNamed:self.thePuzzle.imgFileName];
NSString *urlString = #"http://m.uploadedit.com/b032/1395295852132.txt";
NSString *contents = [TextFileManager readStringFromURL:urlString];
//parse contents
lines = [contents componentsSeparatedByString:#"\n"];
for( int i = 0; i < lines.count; i++)
{
NSString *line = lines[i];
NSLog(#"%d: %#", i, line);
}

SOAP in iOS - Extracting multiple strings from XML

In an iOS program I am making, I am requesting a list of courses with SOAP. This is the reply format
<ListCoursesResponse>
<statusMessage xmlns="xxx">string</statusMessage>
<courseID xmlns="xxx">string</courseID>
<courseTitle xmlns="xxx">string</courseTitle>
</ListCoursesResponse>
<ListCoursesResponse>
<statusMessage xmlns="xxx">string</statusMessage>
<courseID xmlns="xxx">string</courseID>
<courseTitle xmlns="xxx">string</courseTitle>
</ListCoursesResponse>
I am using something along the lines of extrating each separate course as an element in an array, than stepping through the array for each and extracting what is between the Course ID. However, I can't figure out how to extract more than one, as when I return it, it only shows the first course. If I explained this in a bad way, please do tell me so I can try to explain better.
My question is, what's the best way to approach a large list of courses (200+) returned in an XML reponse ?
Edit: Snippet of the code I am using, which only returns 1 ID.
NSString *tag1Open = #"<ListCoursesResponse>";
NSString *tag1Close = #"</ListCoursesResponse>";
NSString *courseIDOpen = #"<courseID xmlns=\"http://drm.mediuscorp.com/\">";
NSString *courseIDClose = #"</courseID>";
result = #"";
NSArray *XMLarray1 = [XMLResult componentsSeparatedByString:tag1Open];
if ([XMLarray1 count] > 1) {
for (int i = 0; i < [XMLarray1 count]; i++) {
NSString *courseIDString = [[[XMLarray1 objectAtIndex:1]componentsSeparatedByString:tag1Close]objectAtIndex:0];
NSArray *courseID = [XMLResult componentsSeparatedByString:courseIDOpen];
if ([courseID count] > 1) {
for (int i = 0; i < [courseID count]; i++) {
courseIDString = [[[courseID objectAtIndex:1]componentsSeparatedByString:courseIDClose]objectAtIndex:0];
}
}
NSLog(#"Course ID: %#",courseIDString);
}
[persArray addObject:result];
for (int i = 0; i < [persArray count]; i++) {
NSLog(#"%#",[persArray objectAtIndex:i]);
}
}
Rather than try to parse the SOAP XML response response yourself using NSString methods, you would be much better off using an XML Parser to handle this task. iOS has a built-in XML Parser called NSXMLParser that is available to you. (There are also numerous third-party XML Parser components available, of both SAX and DOM varieties)
Here is a tutorial that gives an example of using NSXMLParser.

Read from iPhoto Library programmatically

I want to create an Application that connects to the iPhoto Library. So now I would like to read the Events and the pictures themselves from the library.
Is there an elegant / easy way to do this or do I have to manually read the Bundle Structure of the iPhoto User Data?
So far I have only found a picture taker: Is there a UIImagePicker for the Mac Desktop
Update: I found another relevant SO post: Selecting iPhoto images within a cocoa application
You can do it with NSAppleScript. This is some copy/paste from my app, hacked up a bit just to show the idea.
NSAppleEventDescriptor d = .. compile this script ..
#"tell application \"iPhoto\" to properties of albums"
for (int i = 0; i < [d numberOfItems]; i++)
{
NSAppleEventDescriptor *albumDesc = [d descriptorAtIndex:i];
// <NSAppleEventDescriptor: 'ipal'{
// 'ID ':4.265e+09,
// 'purl':'utxt'("http://www.flickr.com/photos/..."),
// 'pnam':'utxt'("Vacation"),
// 'alTy':'pubs',
// 'alCh':[ ],
// 'alPx':'msng' }>
NSString *albumName = [[albumDesc descriptorForKeyword:'pnam'] stringValue];
NSString *albumId = [[albumDesc descriptorForKeyword:'ID '] stringValue];
You can do the same thing to find the images
NSString *scp =
[NSString stringWithFormat:#"tell application \"iPhoto\" to properties of photos of album id %#",
[album objectForKey:#"id"]];
NSAppleEventDescriptor *d = ... compile scp ...
// 1 based!?
for (int i = 1; i <= [d numberOfItems]; i++)
{
NSAppleEventDescriptor *photoDesc = [d descriptorAtIndex:i];
// Yes.. this happens. Not sure why?!
if (!photoDesc)
continue;
// <NSAppleEventDescriptor: 'ipmr'{
// 'pnam':'utxt'("IMG_0058.JPG"),
// 'pwid':768,
// 'pdim':[ 768, 1024 ],
// 'alti':1.79769e+308,
// 'filn':'utxt'("3133889525_10975ba071_b.jpg"),
// 'ipth':'utxt'("/Users/lagnat/Pictures/iPhoto Library/Masters/2010/11/10/20101110-002341/3133889525_10975ba071_b.jpg"),
// 'idat':'ldt '($F57C69C500000000$),
// 'rate':0,
// 'titl':'utxt'("IMG_0058.JPG"),
// 'phit':1024,
// 'itpt':'utxt'("/Users/lagnat/Pictures/iPhoto Library/Thumbnails/2010/11/10/20101110-002341/3133889525_10975ba071_b.jpg.jpg"),
// 'ID ':4.295e+09,
// 'lati':'msng',
// 'pcom':'utxt'(""),
// 'opth':'utxt'("/Users/lagnat/Pictures/iPhoto Library/Masters/2010/11/10/20101110-002341/3133889525_10975ba071_b.jpg"),
// 'lngt':'msng',
// 'tiln':'utxt'("3133889525_10975ba071_b.jpg.jpg") }>
NSString *path = [[photoDesc descriptorForKeyword:'ipth'] stringValue];
NSString *imgname = [[photoDesc descriptorForKeyword:'pnam'] stringValue];
If releasing apps on the App Store you are now required now required to use the Sandbox, this stops the previous AppleScript method from working (the iPhoto app launches but an empty set is returned).
iPhoto libraries consist of a directory structure containing photos, databases and XML files. The contents changes with each version of iPhoto so be careful if manually accessing these files.
If you just want the album details you can parse the file AlbumData.xml
If you would like photos you can browse the Masters folder. The files structure follows date rather than by the sets configured in iPhoto.
More information can be found on the internals of the iPhoto library here:
http://www.fatcatsoftware.com/iplm/Help/iphoto%20library%20internals.html
The majority of the databases are in SQLite format and so can be programmatically accessed through Objective C, though again you can expect schema changes between different versions of iPhoto. The main databases of interest are Library.apdb and Properties.apdb in Database/apdb.
If you still want to use the Apple Script method, here's a version of the previous answer with the Apple script execution part included:
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:#"tell application \"iPhoto\" to properties of albums"];
NSAppleEventDescriptor *d = [script executeAndReturnError:nil];
NSLog(#"photo library count: %ld", (long)[d numberOfItems]);
for (int i = 0; i < [d numberOfItems]; i++)
{
NSAppleEventDescriptor *albumDesc = [d descriptorAtIndex:i];
NSString *albumName = [[albumDesc descriptorForKeyword:'pnam'] stringValue];
NSLog(#"%#", albumName);
}

Set NSMutableArray as data source for NSTableView

I need to view data from NSMutableArray in NSTableView. There is the code:
- (IBAction)StartReconstruction:(id)sender
{
NSMutableArray *ArrayOfFinals = [[NSMutableArray alloc] initWithObjects:nil]; //Array of list with final images
NSString *FinalPicture;
NSString *PicNum;
int FromLine = [TextFieldFrom intValue]; //read number of start line
int ToLine = [TextFieldTo intValue]; //read number of finish line
int RecLine;
for (RecLine = FromLine; RecLine < ToLine; RecLine++) //reconstruct from line to line
{
//Start(RecLine); //start reconstruction
//Create path of final image
FinalPicture = #"FIN/final";
PicNum = [NSString stringWithFormat: #"%d", RecLine];
FinalPicture = [FinalPicture stringByAppendingString:PicNum];
FinalPicture = [FinalPicture stringByAppendingString:#".bmp"];
[ArrayOfFinals addObject:FinalPicture]; // add path to array
}
NSBeep(); //make some noise
}
I need to set ArrayOfFinals as data source for my tableview in my app. I'm noob in cocoa, and I don't know where I need to make connections :(
I saw tutorial on youtube, but it didn't hepl me.
SO is really not a place for step-by-step tutorials.
But on this subject there're many you can find online. Personally, I've found apple tutorial very informative (even if a bit verbose).
You can't really use an array directly as a data source, but you can use an NSArrayController in between and then use bindings to hook them up.
You won't need to write a single line of code for a basic set up.
There are plenty of step-by-step tutorials on the net for this.