How to exctract data from NSURL - iphone

I have the following NSSURL:
myURL - myPlatform://sdk/functionName?key1=value1&key2=value2
How can I get the URL components?
NSString *myPlatform = [myURL...?
NSString *functionName = [myURL...?
NSString *key1 = [myURL...?
NSString *value1 = [myURL...?
NSString *key2 = [myURL...?
NSString *value2 = [myURL...?
I have this code:
- (BOOL)webView:(UIWebView *)webView2 shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url= [request URL];
Log(#"url: %#", url);
NSArray *components = [url pathComponents];
for (NSString *c in components)
Log(#"URL component: %#", c);
}
And this in the log:
url:
url: myPlatform://sdk/functionName?key1=value1&key2=value2
component: /
component: functionName
Thanks in advance

It's in the documentation:
NSString *myPlatfrom = [myURL scheme];
NSString *sdk = [myURL host];
NSString *functionName = [[myURL path] substringFromIndex:1];
NSString *query = [myURL query];
for (NSString *arg in [query componentsSeparatedByString:"&"]) {
NSArray argComponents = [arg componentsSeparatedByString:"="];
NSString key = [argComponents[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString value = [argComponents[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

Related

Change parts of an NSString

I have a urlString that is: http://www.youtube.com/watch?v=5kdEhVtNFPo
I want to be able to change it into this: http://www.youtube.com/v/5kdEhVtNFPo
How would I go about doing that? I'm not sure if I should use the instance methods substringWithRange: or substringFromIndex:
I tried this which removes the first part and just leaves the video id (it removes http://www.youtube.com/watch?v=) now I just need to add http://www.youtube.com/v/ to the start of the string.
NSString *newUrlString = [urlString substringFromIndex:31];
NSString* newUrl = [oldUrl stringByReplacingOccurrencesOfString:#"watch?v=" withString:#"v/"];
Please note that this only works as long as the URL won't contain more instances of the string "watch?v=".
I'll propose a different way that may be more flexible on the inputs you give it:
- (NSString) newURLStringForOldURLString:(NSString *)oldURLString
{
NSString *newURLString = nil;
NSURL *url = [[NSURL alloc] initWithString:oldURLString];
NSString *query = [url query]; /* v=5kdEhVtNFPo */
NSArray *fieldValuePairs = [query componentsSeparatedByString:#"&"];
for (NSString *pair in fieldValuePairs) {
NSArray *components = [pair componentsSeparatedByString:#"="];
NSString *field = [components objectAtIndex:0];
NSString *value = [components objectAtIndex:1];
if ([field isEqualToString:#"v"]) {
newURLString = [NSString stringWithFormat:#"%#://%#:%#/%#/%#", [url scheme], [url domain], [url port], field, value];
break;
}
}
[url release];
return newURLString;
}
To be flexible enough, you could use NSRegularExpression:
NSString *str = #"http://www.youtube.com/watch?v=5kdEhVtNFPo";
NSString *pattern = #"((?:http:\\/\\/){0,1}www\\.youtube\\.com\\/)watch\\?v=([:alnum:]+)";
NSString *template = #"$1v/$2";
NSRegularExpression *regexp = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *newStr = [regexp stringByReplacingMatchesInString:str
options:0 range:NSMakeRange(0, [str length]) withTemplate:template];
NSLog(#"Replaced: %#", newStr);
Another alternative :
NSString *str3 = #"http://www.youtube.com/watch?v=5kdEhVtNFPo";
NSString *outputString;
NSRange range = [str3 rangeOfString:#"watch?v="];
if(range.location != NSNotFound)
{
outputString = [str3 stringByReplacingCharactersInRange:range withString:#"v/"];
NSLog(#"%#",outputString);
}

Saving image persistently in within App - iOS

Trying to select image using photo picker and save that image internally in apps folder.
- (void) imagePickerController: (UIImagePickerController *) pickerdidFinishPickingMediaWithInfo: (NSDictionary *) info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToUse;
// Handle a still image picked from a photo album
if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0)
== kCFCompareEqualTo) {
editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
if (editedImage) {
imageToUse = editedImage;
} else {
imageToUse = originalImage;
}
// Do something with imageToUse
//save it
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageName = [documentsDirectory stringByAppendingString:[NSString stringWithFormat:#"%d", myUniqueID]];
NSString *imagePath = [imageName stringByAppendingPathComponent:#".png"];
NSData *webData = UIImagePNGRepresentation(editedImage);
NSError* error = nil;
bool success = [webData writeToFile:imagePath options:NULL error:&error];
if (success) {
// successfull save
imageCount++;
[[NSUserDefaults standardUserDefaults] setInteger:imageCount forKey:#"imageCount"];
NSLog(#"#Success save to: %#", imagePath);
}
else if (error) {
NSLog(#"Error:%#", error.localizedDescription);
}
}
...
}
What I can't figure out is that writeToFile::: returns false but no value is returned in error so I can't figure out whats going wrong. Any help would be greatly appreciated thanks
You're missing a "/". The line:
NSString *imageName = [documentsDirectory stringByAppendingString:[NSString stringWithFormat:#"%d", myUniqueID]];
should be:
NSString *imageName = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d", myUniqueID]];
And the line that says:
NSString *imagePath = [imageName stringByAppendingPathComponent:#".png"];
should be:
NSString *imagePath = [imageName stringByAppendingPathExtension:#"png"];
Update:
And, shouldn't:
NSData *webData = UIImagePNGRepresentation(editedImage);
be the following?
NSData *webData = UIImagePNGRepresentation(imageToUse);

Prevent iCloud Backup

I make and app that the people download content and they can access it offline, it likes a catalogue. But Apple reject it because it baking up in iCloud i I'm doing the following but it seems not working.
Funciones.m
+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL {
const char* filePath = [[URL path] fileSystemRepresentation];
const char* attrName = "com.apple.MobileBackup";
u_int8_t attrValue = 1;
int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
return result == 0;
}
Update.m
- (void)updateImg:(NSString *)tipo {
//tomamos el ultimo update
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSTimeInterval time = [defaults doubleForKey:#"lastUpdate"];
NSLog(#"%f", time);
CatalogoAppDelegate *app = [[UIApplication sharedApplication] delegate];
NSString *post = [NSString stringWithFormat:#"lastUpdate=%f", time];
NSData *postData = [post dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:NO];
NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *url = [NSString stringWithFormat:#"%#iPhone/update%#Img.php", app.serverUrl, tipo];
[urlRequest setURL:[NSURL URLWithString:url]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if(urlData) {
NSString *aStr = [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]autorelease];
//NSLog(#"%#: %#", tipo, aStr);
NSArray *temp = [aStr componentsSeparatedByString:#";"];
//Direccionl Local de la APP
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
for (int i=0; i<[temp count]; i++) {
NSString *tempImg = [NSString stringWithFormat:#"%#", [temp objectAtIndex:i]];
//NSLog(#"%#", tempImg);
//pedimos cada url
NSURL *tempURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#images/%#/%#", app.serverUrl, tipo, tempImg]];
//[Funciones addSkipBackupAttributeToItemAtURL:tempURL];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:tempURL]];
NSLog(#"%#images/%#/%#", app.serverUrl, tipo, tempImg);
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#", docDir, tempImg];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];
NSURL *backUrl = [NSURL fileURLWithPath:pngFilePath];
[Funciones addSkipBackupAttributeToItemAtURL:backUrl];
}
}
[self performSelectorInBackground:#selector(finUpdate) withObject:nil];
}
Any idea what I am doing wrong?
Thanks
setxattr provides a result indicating success or an error, and Apple's addSkipBackupAttributeToItemAtURL: method checks for an error and passes this information back to your code. Your code simply ignores it. Start by determining if it's returning an error or not.
Maybe it's because your app is compatible with iOS 5.0.
Do not backup variable is only available since 5.1. Details here http://developer.apple.com/library/ios/#qa/qa1719/_index.html#//apple_ref/doc/uid/DTS40011342

error in uploading photo on facebook wall using graph API

I am going to work on iphone app which upload the photos on facebook wall.
I am using this code
here
- (void)rateTapped:(id)sender {
NSString *likeString;
NSString *filePath = nil;
if (_imageView.image == [UIImage imageNamed:#"angelina.jpg"]) {
filePath = [[NSBundle mainBundle] pathForResource:#"angelina" ofType:#"jpg"];
likeString = #"babe";
} else if (_imageView.image == [UIImage imageNamed:#"depp.jpg"]) {
filePath = [[NSBundle mainBundle] pathForResource:#"depp" ofType:#"jpg"];
likeString = #"dude";
} else if (_imageView.image == [UIImage imageNamed:#"maltese.jpg"]) {
filePath = [[NSBundle mainBundle] pathForResource:#"maltese" ofType:#"jpg"];
likeString = #"puppy";
}
if (filePath == nil) return;
NSString *adjectiveString;
if (_segControl.selectedSegmentIndex == 0) {
adjectiveString = #"cute";
} else {
adjectiveString = #"ugly";
}
NSString *message = [NSString stringWithFormat:#"I think this is a %# %#!", adjectiveString, likeString];
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me/photos"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addFile:filePath forKey:#"file"];
//[request setFile:filePath withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"photo"];
[request setPostValue:message forKey:#"message"];
[request setPostValue:_accessToken forKey:#"access_token"];
[request setDidFinishSelector:#selector(sendToPhotosFinished:)];
[request setDelegate:self];
[request startAsynchronous];
}
here i got Photo id is: (null)
- (void)sendToPhotosFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *photoId = [responseJSON objectForKey:#"id"];
NSLog(#"Photo id is: %#", photoId);
NSString *urlString = [NSString stringWithFormat:#"https://graph.facebook.com/%#?access_token=%#", photoId, [_accessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *newRequest = [ASIHTTPRequest requestWithURL:url];
[newRequest setDidFinishSelector:#selector(getFacebookPhotoFinished:)];
[newRequest setDelegate:self];
[newRequest startAsynchronous];
}
- (void)getFacebookProfileFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSLog(#"Got Facebook Profile: %#", responseString);
NSString *likesString;
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSArray *interestedIn = [responseJSON objectForKey:#"interested_in"];
if (interestedIn != nil) {
NSString *firstInterest = [interestedIn objectAtIndex:0];
if ([firstInterest compare:#"male"] == 0) {
[_imageView setImage:[UIImage imageNamed:#"depp.jpg"]];
likesString = #"dudes";
} else if ([firstInterest compare:#"female"] == 0) {
[_imageView setImage:[UIImage imageNamed:#"angelina.jpg"]];
likesString = #"babes";
}
} else {
[_imageView setImage:[UIImage imageNamed:#"maltese.jpg"]];
likesString = #"puppies";
}
NSString *username;
NSString *firstName = [responseJSON objectForKey:#"first_name"];
NSString *lastName = [responseJSON objectForKey:#"last_name"];
if (firstName && lastName) {
username = [NSString stringWithFormat:#"%# %#", firstName, lastName];
} else {
username = #"mysterious user";
}
_textView.text = [NSString stringWithFormat:#"Hi %#! I noticed you like %#, so tell me if you think this pic is hot or not!",
username, likesString];
[self refresh];
}
But here am suffered from following error
here in Console i got an error : Got Facebook Photo: {"error":{"message":"(#803) Some of the aliases you requested do not exist: (null)","type":"OAuthException"}}
I tried this by changing various App ID but my problem doesn't solve.
Anyone help me to achieve this.........
Thanks In advance...
You try like this,
NSData *imagedata = UIImageJPEGRepresentation(urPhoto, 10);
[newRequest setPostValue:imagedata forKey:#"data"];
or add image like this,
[newRequest setPostValue:link forKey:#"data"];

load web pages form Array for iphone

i can load web view on button press like this
-(void)buttonEvent:(UIButton*)sender{
NSLog(#"new button clicked!!!");
if (sender.tag == 1) {
NSLog(#"1");
}
if (sender.tag == 2) {
NSLog(#"2");
NSString *path;
NSBundle *thisBundle = [NSBundle mainBundle];
path = [thisBundle pathForResource:#"index2" ofType:#"html"];
NSURL *instructionsURL = [[NSURL alloc] initFileURLWithPath:path];
[webView loadRequest:[NSURLRequest requestWithURL:instructionsURL]];
}
}
but i want to load the path value from my string NSString *filepat=[listItems objectAtIndex:2];
whose value is tab0/index1.html where tab0 is a folder
so how to load from that string plz help
Thanks
// get the app's base directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
// get the dir/filename
NSString *filepat=[listItems objectAtIndex:2];
// concatenate for full path
NSString *filePath = [basePath stringByAppendingString:filepat];
NSURL *instructionsURL = [[NSURL alloc] initFileURLWithPath:filePath];
[webView loadRequest:[NSURLRequest requestWithURL:instructionsURL]];
You could also use a cache like I use - SimpleDiskCache.m - which will fetch URLs from the internet, and cache and fetch them from disk.
// SimpleDiskCache.h
#interface SimpleDiskCache : NSObject { }
+ (void) cacheURL:(NSURL*) url forData:(NSData*)data;
+ (NSData*) getDataForURL:(NSURL*) url;
#end
// SimpleDiskCache.m
#import "SimpleDiskCache.h"
#import "util.h"
#implementation SimpleDiskCache
+ (NSCharacterSet*) getNonAlphaNumericCharacterSet {
static NSCharacterSet* cs;
if (!cs) {
cs = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
cs = [cs retain];
}
return cs;
}
+ (void) cacheURL:(NSURL*) url forData:(NSData*)data {
NSString* filename = [[[url absoluteString] componentsSeparatedByCharactersInSet:
[NSCharacterSet punctuationCharacterSet]] componentsJoinedByString:#""];
NSString * storePath = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];
[data writeToFile:storePath atomically:NO];
}
+ (NSData*) getDataForURL:(NSURL*) url {
NSString* filename = [[[url absoluteString] componentsSeparatedByCharactersInSet:
[NSCharacterSet punctuationCharacterSet]] componentsJoinedByString:#""];
NSString * storePath = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:storePath]) {
return [NSData dataWithContentsOfFile:storePath];
}
return nil;
}
#end