Custom header in NSMutableRequest - iphone

I wants to include my own custom header in the NSMutableRequest. I have used
[request addValue:(some string value) forHTTPHeaderField:(some string value)];
but its not working. Where am i wrong?

Related

How to get page HTML content of Moodle course through webservice

I want to get all the HTML content of the page resources in a Moodle course through a Moodle Webservice. The documentation is missing examples, and discussion threads I have read through don't seem to address this seemingly basic action.
What is the correct webservice function to get page resource HTML content?
The mod_page_get_pages_by_courses function returns information plus HTML content of a given course (if provided) or all courses the user has access to (if courseids is left blank).
Below is a generalized call to the webservice to retrieve all page information of a specific course, assuming you have a Moodle Webservice correctly set up:
https://<your-moodle-url>/webservice/rest/server.php?wstoken=<your-token>&moodlewsrestformat=json&wsfunction=mod_page_get_pages_by_courses&courseids[0]=<your-course-id>
Here's the abbreviated info from the documentation that helped me figure it out:
mod_page_get_pages_by_courses
Returns a list of pages in a provided list of courses, if no list is provided all pages that the user can view will be returned.
Arguments
courseids (Default to "Array ( ) ") - Array of course ids
Response
Note the content entry, which is a HTML string with the page content.
object {
pages list of (
object {
id int //Module id
coursemodule int //Course module id
course int //Course id
name string //Page name
intro string //Summary
introformat int Default to "1" //intro format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN)
introfiles //Files in the introduction text
list of (
//File.
object {
filename string Optional //File name.
filepath string Optional //File path.
filesize int Optional //File size.
fileurl string Optional //Downloadable file url.
timemodified int Optional //Time modified.
mimetype string Optional //File mime type.
isexternalfile int Optional //Whether is an external file.
repositorytype string Optional //The repository type for external files.
}
)content string //Page content
contentformat int Default to "1" //content format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN)
contentfiles //Files in the content
list of (
//File.
object {
filename string Optional //File name.
filepath string Optional //File path.
filesize int Optional //File size.
fileurl string Optional //Downloadable file url.
timemodified int Optional //Time modified.
mimetype string Optional //File mime type.
isexternalfile int Optional //Whether is an external file.
repositorytype string Optional //The repository type for external files.
}
)legacyfiles int //Legacy files flag
legacyfileslast int //Legacy files last control flag
display int //How to display the page
displayoptions string //Display options (width, height)
revision int //Incremented when after each file changes, to avoid cache
timemodified int //Last time the page was modified
section int //Course section id
visible int //Module visibility
groupmode int //Group mode
groupingid int //Grouping id
}
)warnings Optional //list of warnings
list of (
//warning
object {
item string Optional //item
itemid int Optional //item id
warningcode string //the warning code can be used by the client app to implement specific behaviour
message string //untranslated english message to explain the warning
}
)}
Alternative: core_course_get_contents
Found this helpful forum post by Juan Levya that presents an alternative way of getting the page contents as downloadable HTML files. Adapted info from the original post:
The function core_course_get_contents returns:
Sections
Modules in each section (activities or resources)
If the module is a resource it returns a list of the files used by this resource in the "contents" attribute
That attribute is an array of files, there you will have a fileurl attribute that is the download URL for the file. If you are using Web Services you should append the WS token.
Example of URL returned:
https://<your-moodle-url>/webservice/pluginfile.php/29/mod_page/content/index.html?forcedownload=1
You need to modify the URL to download the file by adding your WS token as a query parameter with the key token:
https://<your-moodle-url>/webservice/pluginfile.php/29/mod_page/content/index.html?forcedownload=1&token=<your-token>
This will initialize a download of the resource file.
Get Course Contents Using Webservice is a somewhat related question, however it specifically asks about lesson resources, which have their own dedicated function.

Serializing an object to JSON

I am new to the JSON format, but it looks ideal for what I am attempting. I need to take a custom NSObject (a recipe) and send it via a URL string in an email. The recipient will then open the link in my app and the URL will be parsed.
My existing implementation manually builds a string from the recipe’s details and decodes it on the other end. I would prefer to use something more standard, like JSON.
So far I have added the following method to my Recipe class:
- (NSData *)jsonRepresentation
{
NSDictionary *dictionary = #{#"name":self.name,
#"instructions":self.instructions};
NSError* error;
return [NSJSONSerialization dataWithJSONObject:dictionary
options:NSJSONWritingPrettyPrinted
error:&error];
}
I can successfully log this NSData object using:
[[NSString alloc]initWithData:recipe.jsonRepresentation
encoding:NSUTF8StringEncoding];
However, I can’t yet add my list of ingredients (an NSArray). I attempted to simply use this:
NSDictionary *dictionary = #{ #"name" : self.name,
#"instructions" : self.instructions,
#"ingredients" : self.orderedIngredients };
but on logging, I receive this error:
Invalid type in JSON write (Ingredient)
As you can tell, I’m pretty new at this.
Am I meant to do something to the ingredients array before I add it to the dictionary?
Try this:
NSDictionary *dictionary = #{ #"name" : self.name,
#"instructions" : self.instructions,
#"ingredients" : [self.orderedIngredients valueForKey:#"name"] };
Assuming that self.orderedIngredients is an array with ingredients objects in it and that ingredients has a property called name in it,
[self.orderedIngredients valueForKey:#"name"]
will return an array of all names.
If your list of ingredients array holds custom class objects, you should create a serializer for that class.

Search for a string in a string and make it Bold in the original String

I know how to check if a string (NSString) contains another smaller stringFor this m doing like:
if ([string rangeOfString:#"bla"].location == NSNotFound) {
NSLog(#"string does not contain bla");
} else {
NSLog(#"string contains bla!");
// here I need to make that string bold
}
Apart from this I want if I got that string I want to make it bold in the original string.So, is there any way to make my particular String Bold?
Thanks in advance...
You will have to use NSAttributedString. But problem is displaying NSAttributedString.
In iOS 6.0's label support NSAttributedString but less version will need third party label.
Use TTTAttributedLabel link for NSAttributedString.
Refer ios-using-tttattributedlabel-to-set-two-color-text link for reference.

How to convert JSON to Object

I defined some custom classes, such as Teacher, Student...
Now I receive teacher info (JSON string) from remote server.
How can I convert the JSON string to Teacher object.
In Java, it's easy to implement a common method for all class (Teacher, Student...) with reflect.
But in Objective-C on iOS, the best way I can find is to use Entity of Core Data, which has setValue:forKey method. First I convert the JSON string to NSDictionary, the set the key-value pair in the disctionary to the Entry.
Is there any better ways?
(I'm from China, so maybe my English is poor, sorry!)
First, do you use JSON Parser? (if not, i'd recommend using SBJson).
Second, why not create an initWithDictionary init method in your custom class that returns self object?
These are all good frameworks for JSON parsing to dictionaries or other primitives, but if you're looking to avoid doing a lot of repetitive work, check out http://restkit.org . Specifically, check out https://github.com/RestKit/RestKit/blob/master/Docs/Object%20Mapping.md This is the example on Object mapping where you define mapping for your Teacher class and the json is automagically converted to a Teacher object by using KVC. If you use RestKit's network calls, the process is all transparent and simple, but I already had my network calls in place and what I needed was to convert my json response text to a User object (Teacher in your case) and I finally figured out how. If that's what you need, post a comment and I'll share how to do it with RestKit.
Note: I will assume the json is output using the mapped convention {"teacher": { "id" : 45, "name" : "Teacher McTeacher"}}. If it's not this way, but instead like this {"id" : 45, "name" : "Teacher McTeacher"} then don't worry ... object mapping design doc in the link shows you how to do this...a few extra steps, but not too bad.
This is my callback from ASIHTTPRequest
- (void)requestFinished:(ASIHTTPRequest *)request {
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:[request.responseHeaders valueForKey:#"Content-Type"]]; // i'm assuming your response Content-Type is application/json
NSError *error;
NSDictionary *parsedData = [parser objectFromString:apiResponse error:&error];
if (parsedData == nil) {
NSLog(#"ERROR parsing api response with RestKit...%#", error);
return;
}
[RKObjectMapping addDefaultDateFormatterForString:#"yyyy-MM-dd'T'HH:mm:ssZ" inTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]]; // This is handy in case you return dates with different formats that aren't understood by the date parser
RKObjectMappingProvider *provider = [RKObjectMappingProvider new];
// This is the error mapping provider that RestKit understands natively (I copied this verbatim from the RestKit internals ... so just go with it
// This also shows how to map without blocks
RKObjectMapping* errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]];
[errorMapping mapKeyPath:#"" toAttribute:#"errorMessage"];
[provider setMapping:errorMapping forKeyPath:#"error"];
[provider setMapping:errorMapping forKeyPath:#"errors"];
// This shows you how to map with blocks
RKObjectMapping *teacherMapping = [RKObjectMapping mappingForClass:[Teacher class] block:^(RKObjectMapping *mapping) {
[mapping mapKeyPath:#"id" toAttribute:#"objectId"];
[mapping mapKeyPath:#"name" toAttribute:#"name"];
}];
[provider setMapping:teacherMapping forKeyPath:#"teacher"];
RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:parsedData mappingProvider:provider];
Teacher *teacher = nil;
RKObjectMappingResult *mappingResult = [mapper performMapping];
teacher = [mappingResult asObject];
NSLog(#"Teacher is %# with id %lld and name %#", teacher, teacher.objectId, teacher.name);
}
You can obviously refactor this to make it cleaner, but that now solves all my problems.. no more parsing... just response -> magic -> Object
Specifically, check out https://github.com/fanpyi/jsontooc/blob/master/README.md
This is the example convert JSON data to Objective-C model, use nodejs.

PhoneGap.exec() passing objects between JS and Obj-C

The only way I found to passing objects between the JS and Obj-C it's by encoding the JS object by using JSON.stringify() and pass the json string to PhoneGap.exec
PhoneGap.exec('Alarm.update',JSON.stringify(list));
... and rebuild the object in Obj-C:
NSString *jsonStr = [arguments objectAtIndex:0];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:#"\\\"" withString:#"\""];
jsonStr = [NSString stringWithFormat:#"[%#]",jsonStr];
NSObject *arg = [jsonStr JSONValue];
It's that correct ? there is a better/proper/official way for doing this ?
PhoneGap.exec was designed for simple types. Your way is ok, alternately you can just pass your single object in (would only work for a single object only, see footer about how we marshal the command), and it should be in the options dictionary for the command. Then on the Objective-C side, use key-value coding to automatically populate your custom object with the dictionary.
e.g.
MyCustomObject* blah = [MyCustomObject new];
[blah setValuesForKeysWithDictionary:options];
If you are interested in how PhoneGap.exec works, read on...
* --------- *
For PhoneGap.exec, the javascript arguments are marshaled into a URL.
For the JS command:
PhoneGap.exec('MyPlugin.command', 'foo', 'bar', 'baz', { mykey1: 'myvalue1', mykey2: 'myvalue2' });
The resulting command url is:
gap://MyPlugin.myCommand/foo/bar/baz/?mykey1=myvalue1&mykey2=myvalue2
This will be handled and converted on the Objective-C side. foo, bar, baz are put in the arguments array, and the query parameters are put in the options dictionary. It will look for a class called 'MyPlugin' and will call the selector 'myCommand' with the arguments array and options dictionary as parameters.
For further info, see phonegap.js, look at PhoneGap.run_command
I think this is the best way to do it, if not the only way.
The PhoneGap.exec call just takes a NSDictionary of objects under the covers so I don't see of a better way to handle it.
most methods are structured like
- (void)someMethod:(NSArray*)arguments withDict:(NSDictionary*)options {
}