i am building an app that shows a random facebook profile picture but do not know how to make the profile id a random number. I can obviously change it randomly in the code but need it to be random. It is the second NSString down that i need to be random. ANy help would be much appreciated!
- (IBAction) nextImagePush {
NSString *prefix = @"http://graph.facebook.com/";
NSString *profileId = @"517418970";
NSString *suffix = @"/picture?type=large";
NSString* url= [NSString stringWithFormat:@"%@%@%@", prefix, profileId, suffix];
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsO开发者_运维百科fURL:[NSURL URLWithString:url]]];
[imageView setImage:img];
NSString *profileId = [NSString stringWithFormat:@"%0.10u", arc4random()];
NSLog(@"profileId: %@", profileId);
NSLog output:
profileId: 1375609947
Updated to use arc4random_uniform
.
For an unbiased integer within a range:
+ (u_int32_t)randomInRangeLo:(u_int32_t)loBound toHi:(u_int32_t)hiBound {
int32_t range = hiBound - loBound + 1;
u_int32_t random = arc4random_uniform(range);
return loBound + random;
}
NSString *profileId = [NSString stringWithFormat:@"%0.9u", [AppDelegate randomInRangeLo:0 toHi:999999999]];
NSLog(@"profileId: %@", profileId);
NSLog output:
profileId: 2500425665
Using SecRandomCopyBytes will require including the header file:
#import <Security/SecRandom.h>
and the Framework:
Security.framework.
Better yet for versions or OS X >= 10.7 or iOS >= 4.3 use arc4random_uniform
+ (u_int32_t)randomInRangeLo:(u_int32_t)loBound toHi:(u_int32_t)hiBound
{
int32_t range = hiBound - loBound + 1;
return loBound + arc4random_uniform(range);
}
to generate random numbers in a fixed interval you can use arc4random()%x. x represents the maximum number you will want to obtain. Of course there are other ways but this one works great.
It's easy to pick a random integer with a function such as rand(3)
, random(3)
, or arc4random(3)
and then use +[NSString stringWithFormat:]
to turn that into a string using the %u
format specifier.
What's much harder is ensuring that the integer you pick corresponds to a valid Facebook user ID:
- Does Facebook document anywhere what the possible valid IDs are?
- Are they always within a certain range?
- Are all IDs in that range valid?
- Is there any way to query the range of valid IDs?
If the answer to all of those questions is "yes", then you can do it, otherwise it's going to be next to impossible unless Facebook provides an API for what you want, which I think is unlikely.
精彩评论