NSURL *url;
NSData *data;
NSString *blork;
url = [NSURL URLWithString: #"http://www.mycompanyaddress.com/identity_check.jsp?cliId=A-00000&security_key=00000"];
data = [url resourceDataUsingCache: NO];
blork = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding];
UIAlertView *testMessage = [[UIAlertView alloc] initWithTitle: #"From Server: " message: blork delegate: self cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[testMessage show];
[testMessage release];
RESOURCEDATAUSINGCACHE is now a deprecated function..otherwise it worked like a charm
you can use -
NSData *data = [NSData dataWithContentsOfURL:url];
and as document says
Use NSURLConnection instead of this method.
Related
I am making a call to an online php from my iOS app. In my output window I see the JSON Response with the data. But I need to store the NSString in my userdefaults but it is coming up NULL.
In this code the NSLog(#"JSON Response is %#", responseData); returns the json data just fine and I see the ipixid. But in the NSLog (#"ipixid is %#", ilixid); it returns ipixid is (null)
NSString *post =[[NSString alloc] initWithFormat:#"email=%#", strValue];
NSLog(#"PostData: %#",post);
NSURL *url1=[NSURL URLWithString:#"http://www.ipixsocial.com/membership/getresult.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url1];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"JSON Response is %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
// NSString *username = [(NSString *) [jsonData objectForKey:#"email"]init];
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"uid"] integerValue];
NSString* ipixid = [jsonData objectForKey:#"ipixid"];
[[NSUserDefaults standardUserDefaults] setObject:ipixid forKey:#"ipixid"];
NSLog (#"ipixid is %#", ipixid);
Don't ignore the "error" parameter you're passing to the parser. Also check that "jsonData" is not nil. I'm think that parsing is failing and because you're ignoring it and assuming jsonData is valid you're getting nil for [jsonData objectForKey:#"ipixid"];
I have an iPad that has a routine to create a pdf and send as an attachment to an email. It all seems to work with the email composer opening showing the pdf document attached. However when tested on an iPad, when the email is received there is no attachment. Any ideas?
[mailComposer addAttachmentData:data mimeType:#"application/pdf" fileName:#"pdffile.pdf"];
[self presentViewController:mailComposer animated:YES completion:nil];
Many thanks
Detail:
The pdf file is created and called pdffile.pdf. The following is the full email routine:
MFMailComposeViewController *mailComposer;
mailComposer = [[MFMailComposeViewController alloc] init];
mailComposer.mailComposeDelegate = self;
[mailComposer setModalPresentationStyle:UIModalPresentationFormSheet];
[mailComposer setSubject:[NSString stringWithFormat: #"i-observe Lesson Observation for: %s", "date"]];
[mailComposer setMessageBody:[NSString stringWithFormat: #"i-observe Lesson Observation for: %s", "name"] isHTML:NO];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [documentsDirectory stringByAppendingFormat:#"pdffile.pdf"];
NSMutableData *data=[NSMutableData dataWithContentsOfFile:file];
[mailComposer addAttachmentData:data mimeType:#"application/pdf" fileName:#"pdffile.pdf"];
[self presentViewController:mailComposer animated:YES completion:nil];
Try This Method:
if([MFMailComposeViewController canSendMail]){
MFMailComposeViewController *mail=[[MFMailComposeViewController alloc]init];
mail.mailComposeDelegate=self;
[mail setSubject:#"Email with attached pdf"];
NSString *newFilePath = #"get path where the pdf reside";
NSData * pdfData = [NSData dataWithContentsOfFile:newFilePath];
[mail addAttachmentData:pdfData mimeType:#"application/pdf" fileName:#"yourpdfname.pdf"];
NSString * body = #"";
[mail setMessageBody:body isHTML:NO];
[self presentModalViewController:mail animated:YES];
[mail release];
}
else
{
NSLog(#"Message cannot be sent");
}
The next solutions is based assuming that the pdf file is in your main bundle:
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *myFile = [mainBundle pathForResource: #"RealNameofFile" ofType: #"pdf"];
NSData *pdfD = [NSData dataWithContentsOfFile:myFile];
[mailViewController addAttachmentData:pdfData mimeType:#"application/pdf" fileName:#"Nametodisplayattached.pdf"];
make sure that the file has the same name as the table cell
How would one do this? I know just merging NSData doesn't work.
Playing with NSAttributedString should work, something like the code shown below
This is a very quick and dirty way to merge many RTF files together
- (void)mergeRTF:(NSURL*)rtf1 :(NSURL*)rtf2 :(NSURL*)merged {
NSMutableDictionary *options = [NSMutableDictionary dictionary];
[options setObject:[NSNumber numberWithUnsignedInteger:NSUTF8StringEncoding]
forKey:NSCharacterEncodingDocumentOption];
NSDictionary *docAttrs = nil;
NSError* error = nil;
NSAttributedString *rtfText1 = [[NSAttributedString alloc] initWithURL:rtf1
options:options
documentAttributes:&docAttrs
error:&error];
NSAttributedString *rtfText2 = [[NSAttributedString alloc] initWithURL:rtf2
options:options
documentAttributes:&docAttrs
error:&error];
NSMutableAttributedString* whole = [[NSMutableAttributedString alloc] initWithAttributedString:rtfText1];
[whole appendAttributedString:rtfText2];
NSData* data = [whole RTFFromRange:NSMakeRange(0, whole.length) documentAttributes:nil];
[data writeToURL:merged atomically:YES];
}
I am working on my new iPhone application,in that I need the datas and addresses from one url and from anther url I need to get the images. These two results are in the form of json response data but I am getting only the result for the datas....
Here is my code
- (void)viewDidLoad
{
jsondataimg=[[NSMutableString alloc] initWithString:#""];
#####for this url i'm not getting the result##########
NSString *urlimg = [NSString stringWithFormat:#"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%#",name];
//NSLog(#"%#",urlimg);
NSURL *url1= [NSURL URLWithString:urlimg];
NSURLRequest *request1 = [[NSURLRequest alloc] initWithURL: url1];
NSURLConnection *connection1 = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
jsonData = [[NSMutableString alloc] initWithString:#""];
NSString *urlString = [NSString stringWithFormat: #"https://maps.googleapis.com/maps/api/place/details/json?reference=%#&sensor=false&key=your key",selectedname];
NSLog(#" the name is%#",selectedname);
NSLog(#" the reference is%#",selectedrefer);
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
[connection1 release];
[request1 release];
[super viewDidLoad];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *partialData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *partialData1 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[jsondataimg appendString:partialData1];
[jsonData appendString:partialData];
[partialData release];
[partialData1 release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
# pragma mark for fetching the image urls
NSDictionary *imageurls=[jsondataimg JSONValue];
NSDictionary*images=[imageurls objectForKey:#"responseData"];
NSLog(#"%#",images);
##########here null value is displaying#######
#pragma mark for fetching the datassss
NSDictionary *filesJSON = [jsonData JSONValue];
NSDictionary *address1 = [filesJSON valueForKey:#"result"];
NSLog(#"Found %#",address1);
}
Just use this no need to set delegate methods nsurl connections.. you will get the data...and same for next one.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=mumbai"]]];
NSURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strResponse = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// NSLog(#"%#",strResponse);
SBJSON *sbJason = [[SBJSON alloc] init];
NSMutableDictionary *getPlaceList = [sbJason objectWithString:strResponse];
Check my app if you don't really understand ( Quick Notes!) But here it goes. My app is a notes app so it allows the user to select from few different kinds of note colors and designs below. When the user selects one, it changes the note above to what ever they set it to. So i need a button that will save the picture they selected, and when the leave the view and come back they can click the load button and the same image they selected will appear. I am using Xcode 4.3.
NSImageView is what your looking for.
This contains info on saving the file (look at the answer with code): Implement drag from NSImageView and save image to a file
The Code:
-(IBAction)saveImageButtonPushed:(id)sender
{
NSBitmapImageRep *rep;
NSData *data;
NSImage *image;
[self lockFocus];
rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[self frame]];
[self unlockFocus];
image = [[[NSImage alloc] initWithSize:[rep size]] autorelease];
[image addRepresentation:rep];
data = [rep representationUsingType: NSPNGFileType properties: nil];
//save as png but failed
[data writeToFile: #"asd.png" atomically: NO];
//save as pdf, succeeded but with flaw
data = [self dataWithPDFInsideRect:[self frame]];
[data writeToFile:#"asd.pdf" atomically:YES];
}
//......
#end
To load an image:
The Code:
NSImage loadedImage = [[NSImage alloc] initWithContentsOfFile: NSString* filePath]
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMddHHmmss"];
NSDate *date = [[NSDate date] dateByAddingTimeInterval:1];
profile_img = [NSString stringWithFormat:#"%#.png",[dateFormatter stringFromDate:date]];
[profile_img retain];
NSLog(#"formattedDateString: %#",profile_img);
NSData *imageToUpload = UIImagePNGRepresentation(Img_View.image);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:ServerPath]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"Upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"file" fileName:profile_img mimeType:#"image/png"];
}];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation2, id responseObject)
{
NSString *response = [operation2 responseString];
NSLog(#"response: [%#]",response);
NSString *post = [NSString stringWithFormat:#"Images=%#",profile_img];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [post length]];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#Gallery.php",ServerPath]];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request1 setHTTPMethod:#"POST"];
NSLog(#"%#", post);
[request1 setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request1 setHTTPBody:postData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];
NSString *responseString = [[[NSString alloc] initWithData:returnData
encoding:NSUTF8StringEncoding] autorelease];
responseString = [responseString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#",responseString);
if([responseString isEqualToString:#"Entered data successfully"])
{
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"Image Share" message:#"Image Share SuccessFully" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil, nil];
[Alert show];
[Alert release];
}
else
{
}
} failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
NSLog(#"error: %#", [operation2 error]);
}];
[operation2 start];