Obj C UIWebView with Variable URL Search Query - objective-c

How do you use a URL and be able to change part of the URL? I'm new at Objective C.
Errors at url in all spots!
restaurants is my UIWebView, zip is my UITextField, restlabel is my UILabel.
-(void)load {
url = [[NSString alloc] initWithFormat:#"http://www.example.com/search?query=%#", restlabel.text];
}
-(IBAction)gourl {
restlabel.text = [NSString stringWithFormat:#"%#", [zip text]];
[restaurants loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}

You have to read the text from the text field and build the URL in your gourl method, not in the load method.
-(IBAction)goToURL {
url = [[NSString alloc] initWithFormat:#"http://www.example.com/search?query=%#", restlabel.text];
[restaurants loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
You can't define a string with a placeholder that will be dynamically changed (I think that was what you were trying to do). You build a string with a "snapshot" of the variables you are referencing.

Found my own answer.
-(IBAction)gorest {
restlabel.text = [NSString stringWithFormat:#"%#", [zip text]];
NSString *url;
url = [[NSString alloc] initWithFormat:#"http://maps.google.com/maps?q=Restaurants+in+%#", restlabel.text];
[restaurants loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
next.hidden = NO;
}

Related

load data from cache with NSURL doesn't work

i'm trying to load a photo from my cache directory.
this is the code where i write the photo into a cache folder:
+(BOOL)writeAData:(NSData *)imageData atURL:(NSURL *)fileUrl
{
return [imageData writeToURL:fileUrl atomically:YES];
}
this code works fine, but i have problems when i try to load the code from the cache folders:
i use the method initWithContentsOfURL inside a block:
NSData *imageData = [[NSData alloc] initWithContentsOfURL:self.imageUrl];
this is the format of url
file://localhost/Users/MarcoMignano/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/0E8E54D8-9634-41CF-934B-A7315411F12F/Library/Caches/image_cache/Meyer%20Library.jpg
the URL is correct, but when i try to use the method above i get this error:
..... [__NSCFString isFileURL]: unrecognized selector sent to instance 0x8a0c5b0 .....
that is the code when i take the url of my model:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
self.photos = [PhotoAlreadyDisplayed getAllPicture];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([sender isKindOfClass:[UITableViewCell class]]) {
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
if (indexPath) {
if ([segue.identifier isEqualToString:#"Show Image"]) {
if ([segue.destinationViewController respondsToSelector:#selector(setImageUrl:)]) {
NSURL *url = [[self.photos objectAtIndex:indexPath.row] valueForKey:#"url"];
[segue.destinationViewController performSelector:#selector(setImageUrl:) withObject:url];
[segue.destinationViewController setTitle:[self titleForRow:indexPath.row]];
}
}
}
}
}
whats wrong with the URL? how can i fix it? thank you
i have find the solution:
when i load the url for the model, i need to initialize the url using fileURLWithPath method:
NSURL *url = [NSURL fileURLWithPath:[[self.photos objectAtIndex:indexPath.row] valueForKey:#"url"]];
Now all works fine, thank you so much for yours help
[NSData initWithContentsOfURL:] is expecting an NSURL as the argument passed in. It looks like you might be passing in a string, rather than an NSURL. Is this the case?
EDIT: Just humour me - try replacing
NSData *imageData = [[NSData alloc] initWithContentsOfURL:self.imageUrl];
with
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:self.imageUrl]];
What happens?
Though it doesn't look like you're returning successfully from initWithContentsOfURL:, but the snippet below may be of use to others:
NSError *error;
NSData *data = [[NSData alloc] initWithContentsOfURL:TestURL options:0 error:&error];
if(data) {
NSLog(#"Success");
}
else {
NSLog(#"Failed: %#", Error);
}
solution: when i load the url for the model, i need to initialize the url using fileURLWithPath method:
NSURL *url = [NSURL fileURLWithPath:[[self.photos objectAtIndex:indexPath.row] valueForKey:#"url"]];
Now all works fine, thank you so much for yours help

iOS: Show PDF in WebView

I´m trying to show a pdf in a webview, but the webview is always white / blank.
if i log the path from the local file, it can be logged, so the file is there..
Here is my code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"fileName" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
(webView is an iboutlet)
Maik
Please make sure the User Interaction Enabled & Multiple Touch are enabled.
Your targetURL is maybe nil, please debug this.
If the targetUrl is nil, this is maybe the 'path' has space.
So you should encode the path:
//Encode Url
+(NSString *) urlEncodeString:(NSString *) str
{
return [str stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
}
Controlling the whole characters rather than not just the space is more appropriate.Try this one for encoding the path of a file.
-(NSString *)urlenc:(NSString *)val{
CFStringRef safeString =
CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)val,
NULL,
CFSTR("/%&=?$#+-~#<>|*,.()[]{}^!şığüöçĞÜŞİÖÇ"),
kCFStringEncodingUTF8);
return [NSString stringWithFormat:#"%#", safeString];
}

UItextFields Data to JSON

i have two UItextFields, userNameTextField and passwordTextField and a UIbutton connection. I would like to have what the user typed in the userNametextField and the passwordTextField, How i can do this please ?? thanks for your answer.
#pragma mark - User auhtentification
-(IBAction)userAuthentificate{
BOOL loginValid = YES;
BOOL passwordValid = YES; // Not specified yet
// contrioll d'interfac__ on test login et password
if (loginValid && passwordValid) {
NSString *jsonRequest = #"{\"login\":\"Samir\",\"password\":\"test\",\"mail\":\"test#gmail.com\"}";
// NSString *jsonRequest = #"{\"login\":\"Samir\",\"password\":\"test\",\"mail\":\"samir#gmail.com\",\"editor\":\"1\"}";
NSString *request_url =#"http:.../register"; // Url WS
NSURL *url = [NSURL URLWithString:request_url];
self.currentRequest = [ASIFormDataRequest requestWithURL:url];
currentRequest.delegate =self;
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[self.currentRequest appendPostData:requestData];
[self.currentRequest setRequestMethod:#"POST"];
[self.currentRequest startSynchronous];
}
}
You can put something like this in the place of your jsonRequest string (the code uses the SBJson framework):
NSDictionary *container = [[NSDictionary alloc] initWithObjectsAndKeys:
[loginTextField text], #"login",
[passwordTextField text], #"password",
[mailTextField text], #"mail"];
NSString *jsonString = [container JSONRepresentation];
// don't forget to release container if not using ARC AFTER creating the NSData object
How about a simple string replacement?
NSString *jsonRequest = [NSString stringWithFormat:#"{\"login\":\"%#\",\"password\":\"%#\",\"mail\":\"%#\"}", userNameTextField.text, passwordTextField.text, emailtextField.text];
Use
NSString *jsonRequest = [NSString stringWithFormat:#"{\"login\":\""%#"\",\"password\":\""%#"\",\"mail\":\"test#gmail.com\"}",userNameTextField.text,passwordTextField.text];

Objective C - attachments via MFMailComposeViewController not showing up

I'm trying to attach a wav-file from an iOS application but the attachment is not delivered even though it's visible in the composed mail.
Heres the related code:
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:NSLocalizedString(#"mailTopic", nil)];
[controller setMessageBody:NSLocalizedString(#"mailBody", nil) isHTML:YES];
NSString *wavPath = [self exportAssetAsWaveFormat:self.myRec.soundFilePath]; // CAF->Wav export
if (wavPath != nil) {
NSLog(#"wavPath: %#", wavPath);
NSData *recData = [NSData dataWithContentsOfFile:wavPath];
NSString *mime = [self giveMimeForPath:wavPath];
[controller addAttachmentData:recData mimeType:mime fileName:#"MySound.wav"];
[self presentModalViewController:controller animated:YES];
[controller release];
}
}
-(NSString *) giveMimeForPath:(NSString *)filePath {
NSURL* fileUrl = [NSURL fileURLWithPath:filePath];
NSURLRequest* fileUrlRequest = [[NSURLRequest alloc] initWithURL:fileUrl cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:.1];
NSURLResponse* response = nil;
[NSURLConnection sendSynchronousRequest:fileUrlRequest returningResponse:&response error:nil];
NSString* mimeType = [response MIMEType];
NSLog(#"MIME: %#", mimeType);
[fileUrlRequest release];
return mimeType;
}
NSLog results:
NSLog(#"wavPath: %#", wavPath); -> "wavPath: /var/mobile/Applications/71256DCA-9007-4697-957E-AEAE827FD97F/Documents/MySound.wav"
NSLog(#"MIME: %#", mimeType); -> "MIME: audio/wav"
The file path seams to be ok (see NSLog data), and the mime type set to "audio/wav".. Cant figure this out..
The error was that the wav-file was not 100% written by the time I create NSData out of it.. duuuh
Thanks for the effort guys
Maybe the destination is stripping attachments of that type? Did you try manually sending a message with a .wav and see if it works? I had the same problem trying to send to Zendesk. Turns out they strip attachments for some mimetypes.

Want to split the JSON from the URL not the response

I want to split the json part from this URL in my iPhone application.
http://vkontakte.ru/login_success.html#session={"expire":"1272008089","mid":"100172","secret":"9c8d8f0305","sid":"1131703552161ae352a1256402e3140d7cbde41b1602a93d15472c82"}
I tried and and saved the JSON into a NSString but what i am getting is
http://vkontakte.ru/api/login_success.html?session=%7B%22mid%22:113158415,%22secret%22:%227ce58bfcd3%22,%22sid%22:%2203831b43c1bb992f9477efbfe96e83f6ecff1c1b661315ac0a20719cf57a44%22,%22expire%22:0%7D
This is not coming in JSOn Format. Below is my code
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
NSError* error;
NSLog (#"json path %#",url);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request1 = [NSURLRequest requestWithURL:url];
NSString *json_string = [url absoluteString];
NSArray *arr = [json_string componentsSeparatedByString:#"="];
json_string = [arr objectAtIndex:1];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [json_string JSONValue];
NSLog(#"%#",error);
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey:#"secret "], [[status objectForKey:#"mid"] objectForKey:#"sid"]);
}
return YES;
}
How can move further?
Try replacing:
NSString *json_string = [url absoluteString];
with
NSString *json_string = [[url absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];.
That's a really strange thing you're doing, though. Why does the URL have JSON in it?