『壹』 ios開發怎麼用定時器進行網路請求
看下是不是你需要的答案(實在搞不定,可以到我們27773技術眾包平台,顧問能幫你找合適的技術牛人)?
如何通過URL獲取json數據
第一種,利用AFJSONRequestOperation,官方網站上給的例子:
NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURL *url = [NSURL URLWithString:[str :NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 從URL獲取json數據
AFJSONRequestOperation *operation1 = [AFJSONRequestOperation :requestsuccess:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary* JSON) {
NSLog(@"獲取到的數據為:%@",JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id data) {
NSLog(@"發生錯誤!%@",error);
}];
[operation1 start];
第二種方法,利用AFHTTPRequestOperation 先獲取到字元串形式的數據,然後轉換成json格式,將NSString格式的數據轉換成json數據,利用IOS5自帶的json解析方法:
NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURL *url = [NSURL URLWithString:[str :NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *html = operation.responseString;
NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
id dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"獲取到的數據為:%@",dict);
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"發生錯誤!%@",error);
}];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];
如果發生Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x14defc80 {NSUnderlyingError=0x14deea10 "bad URL", NSLocalizedDescription=bad URL這個錯誤,請檢查URL編碼格式。有沒有進行:NSUTF8StringEncoding
如何通過URL獲取圖片
非同步獲取圖片,通過隊列實現,而且圖片會有緩存,在下次請求相同的鏈接時,系統會自動調用緩存,而不從網上請求數據。
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 100.0f, 100.0f, 100.0f)]; [imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"]placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]]; [self.view addSubview:imageView];
上面的方法是官方提供的,還有一種方法,
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.scott-sherwood.com/wp-content/uploads/2013/01/scene.png"]];
AFImageRequestOperation *operation = [AFImageRequestOperation :requestimageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
self.backgroundImageView.image = image;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Error %@",error);
}];[operation start];
如果使用第一種URLWithString: placeholderImage:會有更多的細節處理,其實實現還是通過AFImageRequestOperation處理,可以點擊URLWithString: placeholderImage:方法進去看一下就一目瞭然了。所以我覺得還是用第一種好。
如何通過URL獲取plist文件
通過url獲取plist文件的內容,用的很少,這個方法在官方提供的方法裡面沒有
NSString *weatherUrl = @"http://www.calinks.com.cn/buick/kls/Buickhousekeeper.plist";
NSURL *url = [NSURL URLWithString:[weatherUrl :NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[ addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];
*operation = [ :request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList) {
NSLog(@"%@",(NSDictionary *)propertyList);
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList) {
NSLog(@"%@",error);
}];[operation start];
如果稍不留神,可能就出現Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {(
"application/x-plist"
)}, got text/plain" UserInfo=0x16e91ce0 {NSLocalizedRecoverySuggestion=...
...
, = { }, NSErrorFailingURLKey=, NSLocalizedDescription=Expected content type {(
"application/x-plist"
)}, got text/plain, = { URL: } { status code: 200, headers {
"Accept-Ranges" = bytes;
Connection = "keep-alive";
"Content-Length" = 974;
"Content-Type" = "text/plain";
Date = "Sat, 25 Jan 2014 07:29:26 GMT";
Etag = ""1014c2-3ce-4ee63e1c80e00"";
"Last-Modified" = "Wed, 25 Dec 2013 23:04:24 GMT";
Server = "nginx/1.4.2";} }}
可能還會出現亂碼,解決辦法就是[ addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];
如何通過URL獲取XML數據
xml解析使用AFXMLRequestOperation,需要實現蘋果自帶的NSXMLParserDelegate委託方法,XML中有一些不需要的協議格式內容,所以就不能像json那樣解析,還得實現委託。我之前有想過能否所有的XML鏈接用一個類處理,而且跟服務端做了溝通,結果很不方便,效果不好。XML大多標簽不同,格式也不固定,所以就有問題,使用json就要方便的多。
第一步;在.h文件中加入委託NSXMLParserDelegate
第二步;在.m文件方法中加入代碼
NSURL *url = [NSURL URLWithString:@"http://113.106.90.22:5244/sshopinfo"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFXMLRequestOperation *operation =
[AFXMLRequestOperation :request success:^(NSURLRequest *request,NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = self;
[XMLParser setShouldProcessNamespaces:YES];
[XMLParser parse];
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
NSLog(@"%@",error);
}];
[operation start];
第三步;在.m文件中實現委託方法
//在文檔開始的時候觸發
-(void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(@"解析開始!");
}
//解析起始標記
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
NSLog(@"標記:%@",elementName);
}
//解析文本節點
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
NSLog(@"值:%@",string);
}
//解析結束標記
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
NSLog(@"結束標記:%@",elementName);
}
//文檔結束時觸發
-(void) parserDidEndDocument:(NSXMLParser *)parser{
NSLog(@"解析結束!");