upload plist file on server in iphone - iphone

i have created a plist file other than the default one that exists.
Can i upload this plist file onto the server
I tried ASIFormDataRequest.
I was able to upload the image and text file but when i try it with plist it throws error at point shown in bold:
Code:
networkQueue = [[ASINetworkQueue queue] retain];
NSString *filePath = [[[NSBundle mainBundle]
resourcePath] stringByAppendingPathComponent:
[#"test" stringByAppendingString:#".plist"]];
ASIFormDataRequest *request =[ASIFormDataRequest
requestWithURL:[NSURL URLWithString:#"http://allseeing-i.com/ignore"]];
[request setPostValue:#"my_test" forKey:#"share_test"];
[request setFile:filePath
withFileName:[test stringByAppendingString:
#".plist"] andContentType:#"propertylist/plist" forKey:#"mytest"];
[request setDelegate:self];
[request setDidFailSelector:#selector(requestFailed:)];
[request setDidFinishSelector:#selector(gotTheResponse:)];
[networkQueue addOperation: request];
[networkQueue go];
is it really possible?
or should i go ahead with xml
though plist is also an xml format
but still i want to know and what should i do?

networkQueue = [[ASINetworkQueue queue] retain];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
dateString = [formatter stringFromDate:[NSDate date]];
[formatter release];
// hyphen(-) joins file name with the timestamp for uniqueness
NSString *theme_name1 = [[[theme_name stringByAppendingString:#"-"]
stringByAppendingString:dateString]
stringByReplacingOccurrencesOfString:#" " withString:#"_" ];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *path = [documentsPath stringByAppendingPathComponent:
[file_name stringByAppendingString:#".plist"]];
id plist = [[NSDictionary alloc] initWithContentsOfFile:path];
NSData *xmlData = [NSPropertyListSerialization dataFromPropertyList:plist
format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
NSString *xml_string = [[NSString alloc] initWithData:xmlData
encoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"myurl"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"file_name1 forKey:#"filename"];
[request setPostValue:#"user" forKey:#"sharedby"];
[request setPostValue:xml_string forKey:#"data"];
[request setUsername:#"hello"];
[request setPassword:#"world"];
[request setDelegate:self];
[request setDidFailSelector:#selector(requestFailed:)];
[request setDidFinishSelector:#selector(gotTheResponse:)];
[networkQueue addOperation:request];
[networkQueue go];

I got mine to work. Hope this helps somebody :)
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:
[#"test" stringByAppendingString:#".plist"]];
NSDictionary *plist = [[NSDictionary alloc] initWithContentsOfFile:path];
NSData *data = [NSPropertyListSerialization dataFromPropertyList:plist format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"yourUrl"]];
[request addData:data withFileName:#"test.plist" andContentType:#"propertylist/plist" forKey:#"file"];
[request setDelegate:self];
[request startAsynchronous];

If you are correct that xml and text files are fine with the above code then the most likely explanation would seem to be that either the path to the plist file is incorrect, or the file permissions don't allow the file to be read.
You can enable debug in ASIHTTPRequestConfig.h that might reveal more about what's going on.

Related

Request failed 'JSON'

I have JSON format like below i need to post request to sever but the response from the server is error 500.
{"firstName":"Sharath K", "lastName":"babu",
"moMerchantAddresses":[{"email":"abc#abc.co.in"}]} >
NSMutableArray *objects = [NSMutableArray arrayWithObjects:#"Sharath",#"babu",#"[{\"email\":\"abc#abc.co.in\"}]", nil];
NSMutableArray *keys = [NSMutableArray arrayWithObjects:#"firstName",#"lastName",#"moMerchantAddresses", nil];
NSMutableDictionary *jsonDict = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:nil];
NSString *postLength = [NSString stringWithFormat:#"%d",[jsonData length]];
ServiceInterface *service = [[ServiceInterface alloc] init];
service.theDelegate = self;
service.theSuccessMethod = #selector(responseMerchantCreationService:);
service.theFailureMethod = #selector(requestFailedWithError:);
[self addServiceInterfaceToServiceStack:service];
NSString* stringURL = [kBase_URL stringByAppendingString:#"/merchant/create"];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
[request setTimeoutInterval:30.0f];
NSLog(#"request file :: %#",request);
[service startWithRequest:request];
service = nil;
Please Help me in this
It may helps you .
NSMutableDictionary *emailDict = [[NSMutableDictionary alloc] initWithCapacity:0];
[emailDict setObject:#"abc#abc.co.in" forKey:#"email"];
NSMutableArray *emailArr = [[NSMutableArray alloc] init];
[emailArr addObject:emailDict];
NSMutableDictionary *mainDict = [[NSMutableDictionary alloc] initWithCapacity:0];
[mainDict setObject:#"Sharath" forKey:#"firstName"];
[mainDict setObject:#"babu" forKey:#"lastName"];
[mainDict setObject:emailDict forKey:#"moMerchantAddresses"];
Now change this mainDict to NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mainDict options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:nil];

How to post an array value in JSON

I want to post an array value in JSON.
Below is my code :
-(void)getConnection {
NSArray *comment=[NSArray arrayWithObjects:#"aaa",#"bbb",#"ccc",#"hello,yes,tell", nil];
NSURL *aurl=[NSURL URLWithString:#"http://sajalaya.com/taskblazer/staffend/form/iphonearraytest.php"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:aurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:comment options:NSJSONWritingPrettyPrinted error:nil];
NSString *new = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
// NSString *new = [comment JSONString];
// NSArray *new=[comment jsonvalue];
NSString *postString=[NSString stringWithFormat:#"tag=&comment=%#&total=%#",new,#"4"];
NSLog(#"this is post string%#",postString);
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
We don't know your question, but my answer is short and simple. You should use great open source library for this, which is: AFNetworking, and do request like this:
_httpClient = [[AFHTTPClient alloc] initWithBaseURL:[[NSURL alloc] initWithString:#"http://sajalaya.com"]];
[_httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:comment options:NSJSONWritingPrettyPrinted error:nil];
NSString *new = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
new, #"comment",
#4, #"total,
nil];
NSMutableURLRequest *request = [self.httpClient requestWithMethod:#"POST"
path:#"/taskblazer/staffend/form/iphonearraytest.php"
parameters:params];
request.timeoutInterval = 8;
AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// failure
}];
Please use the following Mutable Array Operation componentsJoinedByString.
e.g.
NSMutableArray *commennts=[NSMutableArray arrayWithObjects:#"aaa",#"bbb",#"ccc",#"hello,yes,tell", nil];
NSString* strCommentsJoin = [commennts componentsJoinedByString:#","]; // Please use your separator

URL Decoding of json in ios

I am having 1 webservice in php which is having browser url mentioned bel :
http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01 01:00:00
Now when I try to fetch url in my iphone app, it is taking this url:
http://Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00
This is creating problem.
i have used this code for fetching data from my url.
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"";
NSString *str;
str = #"LastUpdated";
NSString *requestString = [NSString stringWithFormat:#"{\"LastUpdated\":\"%#\"}",str];
// [[NSUserDefaults standardUserDefaults] setValue:nil forKey:#"WRONGANSWER"];
NSLog(#"request string:%#",requestString);
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:#"URLName" ofType:#"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:#"URL"];
//urlLoc = [urlLoc stringByAppendingString:service];
NSLog(#"URL : %#",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"Resp : %#",responseString);
if (respError)
{
// NSString *msg = [NSString stringWithFormat:#"Connection failed! Error - %# %#",
// [respError localizedDescription],
// [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ACTEC"
message:#"check your network connection" delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{
......
}
here,i am getting null response as url is getting decoded...How can I make this solved...
Help me out.
Thanks in advance.
NSString *urlLoc = [[fileContents objectForKey:#"URL"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableData *postData = [NSMutableData data];
NSMutableURLRequest *urlRequest;
[postData appendData: [[NSString stringWithFormat: #"add your data which you want to send"] dataUsingEncoding: NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setURL:[NSURL URLWithString:urlLoc]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSString *temp = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSLog(#"\n\nurl =%# \n posted data =>%#",urlLoc, temp);
check nslog. that which data u send to service.
NSData *response = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"json_string >> %#",json_string);
Maybe this will help you.
hey dear just for an another example i just post my this code..
first Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:
    [NSURL URLWithString:#"http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00"]];
Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request
    returningResponse:nil error:nil];
Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc]
    initWithData:response encoding:NSUTF8StringEncoding];
Parse the JSON response into an object Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil]
And in statuses array you have all the data you need.
i hope this help you...
:)

Send json to php using ASIFormDataRequest

I'm new in iPhone and I'm trying to convert NSMutable array to json string then send this string to php file using request, and then print it again using respond to NSLog to ensure that it has been send successfully. So I wrote the following code in viewDidLoad
NSString *phpUrl = #"http://dt-works.com/eman/bookMarks.php";
NSMutableArray *arrayKey = [[NSMutableArray alloc] initWithObjects:#"one", #"two", #"three", nil];
NSMutableArray *arrayValue1 = [[NSMutableArray alloc] initWithObjects:#"1", #"2", #"3", nil];
NSMutableArray *arrayValue2 = [[NSMutableArray alloc] initWithObjects:#"11", #"22", #"33", nil];
NSDictionary *theReqDictionary1 = [NSDictionary dictionaryWithObjects:arrayValue1 forKeys:arrayKey];
NSDictionary *theReqDictionary2 = [NSDictionary dictionaryWithObjects:arrayValue2 forKeys:arrayKey];
NSMutableArray *myArray = [NSMutableArray arrayWithObjects:theReqDictionary1,theReqDictionary2, nil];
NSString *jsonString = [myArray JSONRepresentation];
NSLog(#"%#", jsonString);
NSDictionary *questions = nil;
NSURL *link = [NSURL URLWithString:[phpUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
[request setPostValue:jsonString forKey:#"jsonString"];
[request setTimeOutSeconds:120];
[request setDelegate:self];
NSError *error = [request2 error];
[request2 startSynchronous];
if (!error) {
NSData *response = [request responseData];
NSString *json = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
questions = [json objectFromJSONString];
NSLog(#"Data: %#", questions);
}
and the code in bookMarks.php is:
$handle = fopen('php://input','r');
$jsonInput = $_POST['jsonString'];
print_r($jsonInput);
but it gives me:
[{"one":"1","two":"2","three":"3"},{"one":"11","two":"22","three":"33"}]
Data: (null)
and I want Data to be as: [{"one":"1","two":"2","three":"3"},{"one":"11","two":"22","three":"33"}]
how to do this??
Try this, instead of posting the JSON string with a key, you need to post it as Data to your script to be read in. Currently in your script you aren't even using $handle for anything...
NSURL *link = [NSURL URLWithString:[phpUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
[request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setTimeOutSeconds:120];
[request setDelegate:self];
And your php code..
$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
$decoded = json_decode($jsonInput,true);
print_r($decoded);

Failed to move file error in ASIHTTPRequest

I am using ASIHTTPRequest for downloading file from server but its giving error
Failed to move file from '/Users/admin/Library/Application
Support/iPhone
Simulator/3.1.3/Applications/8650FFE4-9C18-425C-9CEE-7392FD788E6D/Documents/temp/test.zip.download'
to '/Users/admin/Library/Application Support/iPhone
Simulator/3.1.3/Applications/8650FFE4-9C18-425C-9CEE-7392FD788E6D/Documents/test.zip'
can any body tell mw this error what wrong in my code......
NSURL *url = [NSURL URLWithString:#"http://wordpress.org/latest.zip"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [NSString stringWithFormat:#"%#/test.zip", [dirArray objectAtIndex:0]];
//NSString *tempPath = [NSString stringWithFormat:#"%#test.zip", NSTemporaryDirectory()] ;
NSString *tempPath =[NSString stringWithFormat:#"%#/temp/test.zip.download", [dirArray objectAtIndex:0]];
// The full file will be moved here if and when the request completes successfully
[request setDownloadDestinationPath:path];
[request setTemporaryFileDownloadPath:tempPath];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestWentWrong:)];
[[self queue] addOperation:request]; //queue is an NSOperationQueue
do you already have a temp.zip in that location ?
It also happens if you didn't set the destination path correctly, using this method setDownloadDestinationPath: of ASIHTTPRequest...
Your call
[request setTemporaryFileDownloadPath:tempPath];
is not necessary, and is more than likely the source of your error.