File Name NSString adds unnecessary %20 in space - ios

SOLVED (Thanks Regexident)
I have an app that passes the file path of a PDF to a custom -(id)init init method. It is added to the table and when it is selected, it calls the else statement for a non existent file:
- (void) gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index {
NSLog (#"Selected theArgument=%d\n", index);
UIViewController *viewController = [[[UIViewController alloc]init]autorelease];
{
//if file is built-in, read from the bundle
if (index <= 3)
{
// first section is our build-in documents
NSString *fileURLs = [_documentIconsURLs objectAtIndex:index];
NSLog(#"file url -%#", fileURLs);
viewController = [[[xSheetMusicViewController alloc]initWithContentURL:fileURLs]autorelease];
}
//if file is external, read from URL
else
{
// second section is the contents of the Documents folder
NSString *fileURL = [_documentIconsURLs objectAtIndex:index];
NSLog(#"file url -%#", fileURL);
NSString *path;
NSString *documentsDirectoryPath = [self applicationDocumentsDirectory];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileURL];
if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectoryPath])
{
viewController = [[[xSheetMusicViewController alloc]initWithDocumentURL:fileURL]autorelease];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Failure!" message:#"The Selected File Does Not Exist"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
return;
}
}
[self.navigationController setNavigationBarHidden:YES animated:NO];
[UIView beginAnimations:#"animation" context:nil];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.navigationController.view cache:YES];
[self.navigationController pushViewController:viewController animated:NO];
[UIView commitAnimations];
}
}
So whenever I have a document with no space in it's name, it pushes and inits. But when the file name has a space in it, it says it does not exist. And when I remove the if-else method, it init's, but crashes because the file doesn't exist. I've tried to replace the %20 in the file path with a regular space, but the method continues to call the else part.
So, is the file path not standardized and readable, or is my else method wrong?

As your path appears to be a percentage escaped path string I'd try this:
[fileURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
And I'd rename fileURL to fileURLString to make clear that it's an NSString containing a URL path, not an actual NSURL (which your variable name would falsely imply).
But I'd check the code that populates _documentIconsURLs, as it's probabaly the origin of your problem.

Related

Creating and attaching a .txt file to email in Xcode [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to make an iOS app that makes/creates a text file (.txt) then sends it as an email.
The issue i am having is the data to be encrypted pops up with the error "use of undeclared identifier"
[mailController addAttachmentData:dataToBeEncrypted mimeType:#"text/plain"
Here is my .m file
//
// FileIoViewController.m
// FileIo
//
// Created by Flare gun on 6/24/14.
// Copyright (c) 2014 Flaregunapplications. All rights reserved.
//
#import "FileIoViewController.h"
#interface FileIoViewController ()
#end
#implementation FileIoViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = #"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
if([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc] init];
mailController.mailComposeDelegate =self;
[mailController setSubject:#"Records"];
[mailController setMessageBody:#"" isHTML:YES];
[mailController addAttachmentData:dataToBeEncrypted mimeType:#"text/plain" fileName:#"Records.txt"];
[self presentModalViewController:mailController animated:YES];
[mailController release];
} else {
//Pop up a notification
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Could not send email. Verify Internet conneciton and try again." delegate:nil cancelButtonTitle:#"Done" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
#end
To declare dataToBeEncrypted use something like:
NSData *dataToBeEncrypted = [NSData dataWithContentsOfFile:filename];

I want to use identifiers in .m in other .m (implementation file import) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
On cameraviewcontrolle.mr I take a picture or movie using UIImagePickerController. On completion, I call back to aanvraagviewcontroller.m.
I want to save the the picture by tapping on send button.
My question comes to this I think, how can I import .m file or take the picture/movie to aanvraagviewcontroller.m (I use Parse.com to save my PFObjects)?
This is cameraviewcontroller.m
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
// A photo was taken/selected!
self.image = [info objectForKey:UIImagePickerControllerOriginalImage];
if (self.imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
// Save the image!
UIImageWriteToSavedPhotosAlbum(self.image, nil, nil, nil);
}
}
else {
// A video was taken/selected!
self.videoFilePath = (__bridge NSString *)([[info objectForKey:UIImagePickerControllerMediaURL] path]);
if (self.imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
// Save the video!
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(self.videoFilePath)) {
UISaveVideoAtPathToSavedPhotosAlbum(self.videoFilePath, nil, nil, nil);
}
}
}
[self uploadMessage];
[self dismissViewControllerAnimated:YES completion:nil];
[self.navigationController popToRootViewControllerAnimated:YES];}
- (void)uploadMessage {
NSData *fileData;
NSString *fileName;
NSString *fileType;
if (self.image != nil) {
UIImage *newImage = [self resizeImage:self.image toWidth:320.0f andHeight:480.0f];
fileData = UIImagePNGRepresentation(newImage);
fileName = #"image.png";
fileType = #"image";
}
else {
fileData = [NSData dataWithContentsOfFile:self.videoFilePath];
fileName = #"video.mov";
fileType = #"video";
}
PFFile *file = [PFFile fileWithName:fileName data:fileData];
[file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"An error occurred!"
message:#"Please try sending your message again."
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {// onderdeelAanvraag[#"file"] = file;
// onderdeelAanvraag[#"fileType"] = fileType;
// onderdeelAanvraag[#"recipientIDs"] = self.recipients;
//
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"An error occurred!"
message:#"Please try sending your message again."
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {
// Everything was successful!
[self reset];
}
// }];
}
}];
}
- (void)reset {
self.image = nil;
self.videoFilePath = nil;
[self.recipients removeAllObjects];
}
- (UIImage *)resizeImage:(UIImage *)image toWidth:(float)width andHeight:(float)height {
CGSize newSize = CGSizeMake(width, height);
CGRect newRectangle = CGRectMake(0, 0, width, height);
UIGraphicsBeginImageContext(newSize);
[self.image drawInRect:newRectangle];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resizedImage;
}
This is aanvraagviewcontroller.m (when send button is pressed, i want to save the picture/movie here);
- (IBAction)verstuurAanvraag:(id)sender {
NSString *onderdeelOmschrijving = self.onderdeelOmschrijvingField.text ;
NSString *autoOmschrijving = self.autoOmschrijvingField.text ;
if ([onderdeelOmschrijving length] == 0 ||
[autoOmschrijving length] == 0)
{
UIAlertView *alertView = [[ UIAlertView alloc] initWithTitle:#"Leeg veld" message:#"Vul de lege velden in" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
}
else {
PFObject *onderdeelAanvraag = [PFObject objectWithClassName:#"Aanvragen"];
[onderdeelAanvraag setObject:[PFUser currentUser] forKey:#"Aanvrager"];
onderdeelAanvraag[#"OnderdeelOmschrijving"] = onderdeelOmschrijving;
onderdeelAanvraag[#"AutoOmschrijving"] = autoOmschrijving;
NSDate *date = [NSDate date];
onderdeelAanvraag[#"Datum"] =date;
onderdeelAanvraag[#"file"] = file;
onderdeelAanvraag[#"fileType"] = fileType;
onderdeelAanvraag[#"recipientIDs"] = self.recipients;
// Get random number between 0 and 999999
int nummer = arc4random() % 100000;
NSLog(#"nieuw nummer %d", nummer);
[onderdeelAanvraag setObject:[NSNumber numberWithInt:nummer] forKey:#"AanvraagNummer"];
[onderdeelAanvraag saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Sorry!" message: [error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {
[self performSegueWithIdentifier:#"showRecipients" sender:self];
}
}];
}
}
I SOLVED PASSING UITEXTFIELD TEXT BY THIS ;
I solved passing textfield data passing with the segue method like here ;
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:#"showRecipients"]){
OntvangersViewController *controller;
controller = [segue destinationViewController];
controller.onderdeelOmschrijvingField = self.onderdeelOmschrijvingField;
controller.autoOmschrijvingField = self.autoOmschrijvingField;
controller.image = self.image;
controller.videoFilePath = self.videoFilePath;
NSLog(#"videofilepath %#", self.videoFilePath);
controller.recipients = self.recipients;
}
}
Your question is muddled and confused.
The code in a .m file is not shared with other .m files.
The whole point of the C .h header file is that the header file can be shared, while the implementation (.c, or .m for Objective C) is private, and not shared.
If you want a value to be visible to another class, or another object of the same class, you should define a property in the header file.
If you want to pass a value from one view controller to another, this topic has been covered Ad nauseam here and on other forums. There are at least 2 comments on your post pointing you to other threads covering the topic.

ZBar SDK slowing down in IOS7

I am trying to implement some qr code reader using ZBar.
After a while I did manage to do reading, but after several readings the app tends to get slower and slower (until practically unresponsive).
This SDK is compatible with iOS7 ?
Frameworks : libiconv.dylib,libinfo.dylib, QuartzCore, CoreVideo,CoreMedia,AVFoundation,CoreGraphics,UIKit,XCTest
- (IBAction)scan:(id)sender {
//initialize the reader and provide some config instructions
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
[reader.scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 1];
reader.cameraFlashMode=UIImagePickerControllerCameraFlashModeOff;
reader.readerView.zoom = 1.0; // define camera zoom property
//show the scanning/camera mode
[self presentModalViewController:reader animated:YES];
// Do any additional setup after loading the view from its nib.
}
- (void) imagePickerController: (UIImagePickerController*) reader
didFinishPickingMediaWithInfo: (NSDictionary*) info {
//this contains your result from the scan
id results = [info objectForKey: ZBarReaderControllerResults];
//create a symbol object to attach the response data to
ZBarSymbol *symbol = nil;
//add the symbol properties from the result
//so you can access it
for(symbol in results){
//symbol.data holds the value
NSString *upcString = symbol.data;
//print to the console
NSLog(#"the value of the scanned UPC is: %#",upcString);
NSMutableString *message = [[NSMutableString alloc]
initWithString: #"Scanned Barcode: "];
[message appendString:[NSString stringWithFormat:#"%# ",
upcString]];
//Create UIAlertView alert
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Product Barcode" message: message delegate:self
cancelButtonTitle:#"Cancel" otherButtonTitles: nil];
self.viewResult.text = upcString;
[alert show];
//After some time
[alert dismissWithClickedButtonIndex:0 animated:TRUE];
//make the reader view go away
[reader dismissModalViewControllerAnimated: YES];
}
}
EDIT : After 4 or 5 readings, this is the memory and CPU consumption -> http://diogomend.me/images/capt.png. Christ :D
Well, after checking this issue Memory related issue of ZBarReaderViewController in iOS 7, I did manage to solve the problem.
The lines I've added are the following:
(in my viewcontroller.h)
#property (strong,nonatomic) ZBarReaderViewController *reader;
(in my viewcontroller.m)
if(self.reader)
{
[self.reader.readerView stop];
for(UIView *subViews in self.reader.view.subviews)
[subViews removeFromSuperview];
[self.reader.view removeFromSuperview];
self.reader.view = nil;
}
_reader = [ZBarReaderViewController new];

if statement returns TRUE when it should be FALSE on UIWebView request URL

I have a series of if statement s to check whether I'm logged in or not.
- (void)webViewDidFinishLoad:(UIWebView *)webView {
if ([webView.request.URL isEqual:#"http://www.tapgram.com/login"]) {
NSLog(#"on log in page: %#", webView.request.URL);
} else if ([webView.request.URL isEqual:#"http://www.tapgram.com/loginfailed?alert_message=Failed+login&came_from=%2F"]){
NSLog(#"failed log in: %#", webView.request.URL);
[keychainItem resetKeychainItem];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Incorrect Credentials" message:#"It seems that either your username or password is incorrect. Please try agian." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
} else if (![webView.request.URL isEqual:#"http://www.tapgram.com/login"]) {
NSLog(#"logged in: %#", webView.request.URL);
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
ViewController *vc = [storyboard instantiateViewControllerWithIdentifier:#"ViewController"];
[vc setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentViewController:vc animated:YES completion:nil];
}
I get this log:
2013-12-22 21:58:02:054 Tapgram[1096:1547] -[LogInViewController webViewDidFinishLoad:] [Line 151] logged in: http://www.tapgram.com/login
Which means that one of the if statements saying if(![webView.request.URL isEqual:#"http://www.tapgram.com/login"]) returns TRUE when the URL is equal to the one specified. And the NSLog in the if statement proves it.
You're comparing an NSURL object to an NSString, so they aren't the same. You can convert the NSURL object (webView.request.URL) to a string by using NSURL's -absoluteString and compare those or create an NSURL object out of the NSString and compare those.
As an example, you can't compare an NSURL and an NSString object directly. You can use the absoluteString though to compare:
NSString *string = #"http://www.apple.com";
NSURL *url = [NSURL URLWithString:string];
NSURL *url2 = [NSURL URLWithString:string];
if ([url isEqual:string]) {
NSLog(#"String Equal");
} if ([url isEqual:url2]) {
NSLog(#"URL Equal");
} if ([url.absoluteString isEqualToString:string]) {
NSLog(#"Absolute String Equal");
}
Outputs:
URL Equal
Absolute String Equal
You can convert the NSURL to an NSString for string-comparison by adding .absoluteString and using isEqualToString: rather than isEqual:, like this:
if ([webView.request.URL.absoluteString isEqualToString:#"http://www.example.com/test"])

uploadedFile not called

I have an app where I upload a simple .csv file to Dropbox. The files upload perfectly when I send them, but the restClient uploadedFile method is not called. I would like this to use this to display to the user that the file has been uploaded successfully. I seem to remeber it was called the first few times I ran the code, but then it stopped and I can't see why.
Here are some snippets:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) //Cancel
{
}
else if (buttonIndex == 1) //Send
{
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *CCD = [docPath stringByAppendingPathComponent:#"CCD.csv"];
if ([[NSFileManager defaultManager] fileExistsAtPath:CCD])
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *machineName = [defaults objectForKey:#"machineName"];
NSString *fileTitle = [defaults stringForKey:#"setTitle"];
NSMutableString *filePath = [NSMutableString string];
[filePath appendString:docPath];
[filePath appendString:#"/CCD.csv"];
NSString *destDir = #"/";
[SVProgressHUD showWithStatus:[NSString stringWithFormat:#"Sending to %#...", machineName]];
[[self restClient] uploadFile:fileTitle toPath:destDir
withParentRev:nil fromPath:filePath];
}
}
}
- (void)restClient:(DBRestClient*)restClient uploadedFile:(NSString*)filePath {
NSLog(#"File uploaded successfully");
[SVProgressHUD dismiss];
};
As I said, it uploads the file perfectly, I just don't get the call to the uploadedFile method.
Try this way..
#interface ResultClass_vice : UIViewController<DBRestClientDelegate>
{
DBRestClient *restClient;
}
#pragma mark - DropBox
- (void)didPressLink {
// [[DBSession sharedSession]unlinkAll];
if (![[DBSession sharedSession] isLinked]) {
[[DBSession sharedSession] linkFromController:self];
// Session must be linked before creating any DBRestClient objects.
// nstr
UIAlertView *al=[[UIAlertView alloc]initWithTitle:#"" message:#"You must have to Login" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[al show];
[al release];
}
}
- (DBRestClient *)restClient {
if (!restClient) {
restClient =
[[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
restClient.delegate = self;
}
return restClient;
}
- (void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath
from:(NSString*)srcPath metadata:(DBMetadata*)metadata {
//NSLog(#"File uploaded successfully to path: %#", metadata.path);
UIAlertView *alert = [[[UIAlertView alloc]initWithTitle:#"Success" message:#"Your file is successfully uploaded to Dropbox" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil]retain];
[alert show];
[alert release];
}
- (void)restClient:(DBRestClient*)client uploadFileFailedWithError:(NSError*)error {
NSLog(#"File upload failed with error - %#", error);
}
Let me know if you have any problem because I already implemented it.
The main problem is you have changed upload method parameters:
You are using:
- (void)restClient:(DBRestClient*)restClient uploadedFile:(NSString*)filePath {
NSLog(#"File uploaded successfully to path: %#", metadata.path);
}
And you should used:
- (void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath
from:(NSString*)srcPath metadata:(DBMetadata*)metadata {
NSLog(#"File uploaded successfully to path: %#", metadata.path);
}
If you change the number of parameters, you are creating a new function, and therefore, Dropbox SDK will not called it.
I hope this would be helpful

Resources