记得上次写过这篇,不知道跑哪里去了,也不知道看到哪里了,就随着记忆走吧。
那就在此补充一下,项目代码里面,用的是
{
[req setHTTPBody: [postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *httpConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
[httpConnection start];
[httpConnection release];
httpConnection = nil;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//这里用来获取头信息
//NSLog(@"获取头信息");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.recievedData appendBytes:[data bytes] length:[data length]];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//NSLog(@"交互出错");
[[NSNotificationCenter defaultCenter] postNotificationName:notifycationString object:nil];
// NSLog(@"error:%@",error);
//这里表示交互出错
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
}
但是书上,是用这种方式,看上去简单很多,改天得空了,问问牛同事。
NSString *urlAsString = @"http://pixolity.com/post.php";
urlAsString = [urlAsString stringByAppendingString:@"?param1=First"];urlAsString = [urlAsString stringByAppendingString:@"¶m2=Second"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:@"POST"];
NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2";[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection
sendAsynchronousRequest:urlRequestqueue:queuecompletionHandler:^(NSURLResponse *response,
NSData *data,NSError *error) {
if ([data length] >0 &&error == nil){
NSString *html = [[NSString alloc] initWithData:dataencoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@", html);}
else if ([data length] == 0 &&error == nil){
NSLog(@"Nothing was downloaded.");}
else if (error != nil){
NSLog(@"Error happened = %@", error);
}}];
8.4
8.5也看完了,看来理解http协议,对理解这些代码很有帮助。
一口气看到8.9 看例子代码就行,挺简单的
看这个还学会转码了
8.9 Serializing Arrays and Dictionaries into JSON
NSString * testdecode=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
发现公司项目里面的代码,都没有这个条件判断,
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrintederror:&error];
if ([jsonData length] > 0 &&error == nil){
NSLog(@"Successfully serialized the dictionary into data = %@", jsonData);
}
当然很多情况下,会报错,这个时候,就需要对error进行判断了。
8.10
个人觉得地下的代码很有教育意义,简直可以当模板了,有各种异常处理,很好。
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:@"Anthony"
forKey:@"First Name"];
[dictionary setValue:@"Robbins"
forKey:@"Last Name"];
[dictionary setValue:[NSNumber numberWithUnsignedInteger:51]
forKey:@"Age"];
NSArray *arrayOfAnthonysChildren = [[NSArray alloc]
initWithObjects:
@"Anthony's Son 1",
@"Anthony's Daughter 1",
@"Anthony's Son 2",
@"Anthony's Son 3",
@"Anthony's Daughter 2",
nil];
[dictionary setValue:arrayOfAnthonysChildren
forKey:@"children"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization
dataWithJSONObject:dictionary
options:NSJSONWritingPrettyPrinted
error:&error];
if ([jsonData length] > 0 &&
error == nil){
NSLog(@"Successfully serialized the dictionary into data.");
/* Now try to deserialize the JSON object into a dictionary */
error = nil;
id jsonObject = [NSJSONSerialization
JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments
error:&error];
if (jsonObject != nil &&
error == nil){
NSLog(@"Successfully deserialized...");
if ([jsonObject isKindOfClass:[NSDictionary class]]){
NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
NSLog(@"Deserialized JSON Dictionary = %@", deserializedDictionary);
}
else if ([jsonObject isKindOfClass:[NSArray class]]){
NSArray *deserializedArray = (NSArray *)jsonObject;
NSLog(@"Deserialized JSON Array = %@", deserializedArray);
}
else {
/* Some other object was returned. We don't know how to deal
with this situation as the deserializer only returns dictionaries
or arrays */
}
}
else if (error != nil){
NSLog(@"An error happened while deserializing the JSON data.");
}
}
else if ([jsonData length] == 0 &&
error == nil){
NSLog(@"No data was returned after serialization.");
}
else if (error != nil){
NSLog(@"An error happened = %@", error);
}
8.12 正好,这个也可以和项目中的代码做一个对比了
貌似还有点复杂啊,没有json简单,第一次直接看代码,比较费劲了,囧
2了一阵子,回过味来了
//xml 的key
@property (nonatomic, strong) NSString *name;
//xml 的value
@property (nonatomic, strong) NSString *text;
//一堆属性
@property (nonatomic, strong) NSDictionary *attributes;
//子项
@property (nonatomic, strong) NSMutableArray *subElements;
//父项
@property (nonatomic, weak) XMLElement *parent;
在斯坦福的视频里面,白胡子老爷爷也是这么说的。应该是第一个例子里面就说到这个了。这一点也是同事们没有做到的。We want the subElements mutable array to be created only if it is nil when it is accessed,
hence, we place our allocation and initialization code for this property in its own getter
method. If an XML element doesn't have sub elements and we never use that property,then there is no point allocating and initializing a mutable array for that element. Thistechnique is known as lazy allocation.
嗯,不错,lazy allocation。
这几段代码,费了我好久,哎,补充一下吧这样
<weichaotest shuxing="shuxingzhi"/>
这样
<firstName>Anthony</firstName>
还有这样
<person id="1">
</person>
都算是一个
Element。
- (void) parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
这个函数执行的时机,是在解析一个Element开始的时候,所谓开始的时候,没啥好说的,知道什么是element就可以了。
结束就有的说了
- (void) parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName{
self.currentElementPointer = self.currentElementPointer.parent;
}
我的理解是碰到类似与这种字符/>或者</firstName>的时候执行,应该是从头到尾,顺序解析每个element的。没人手把手教理解起来略微费劲。特别是状态不好的时候。