[IOS]网络操作+图片的下载和读取+json数据读取

简介: 如何读取沙盒中的文件,和保存网络资源到沙盒中? -(NSString *)dataFilePath:(NSString*)fileName {     NSArray *paths=NSSearchPathForDirectoriesInDomains(...

如何读取沙盒中的文件,和保存网络资源到沙盒中?

-(NSString *)dataFilePath:(NSString*)fileName

{

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    

    NSString *document=[paths objectAtIndex:0];

    

    return [documentstringByAppendingPathComponent:fileName];

}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection

    //可以下载图片

    [self.datawriteToFile:[selfdataFilePath:@"image.jpg"]atomically:YES];

    self.webView.hidden =YES;

    //将沙盒中的图片加载到界面中

    NSString *path = [selfdataFilePath:@"image.jpg"];

    UIImage *imag = [[UIImagealloc]initWithContentsOfFile:path];

    UIImageView *img = [[UIImageViewalloc]initWithImage:imag];

    CGRect rect = CGRectMake(0,0,320,460);

    img.frame = rect;

    [self.viewaddSubview:img];

}


进入主题,接下来我要实现三个功能:

1.访问网页

2.从网上加载图片资源到本地

3.发送get请求获取到天气预报的接口,然后保存到本地接着是json解析

功能设计:

1.webView的使用

PageViewController.h:

#import <UIKit/UIKit.h>

@interface PageViewController : UIViewController<UIWebViewDelegate>
@property (retain, nonatomic) IBOutlet UIWebView *webView;
- (IBAction)GoClick:(id)sender;
@property (retain, nonatomic) IBOutlet UITextField *txtUrl;
- (IBAction)resignBoardClick:(id)sender;
@property(retain,nonatomic)NSURL *url;
@property(nonatomic,retain)UIAlertView *alert;
@end

PageViewController.m:

//
//  PageViewController.m
//  地图+网络
//
//  Created by 丁小未 on 13-8-27.
//  Copyright (c) 2013年 dingxiaowei. All rights reserved.
//

#import "PageViewController.h"

@interface PageViewController ()

@end

@implementation PageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"页面";
    }
    return self;
}

-(void)pageLoad1:(NSURL *)url
{
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.url = [NSURL URLWithString:@"http://www.baidu.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:self.url];
    [self pageLoad1:self.url];

}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self.alert dismissWithClickedButtonIndex:0 animated:YES];
}

-(void)webViewDidStartLoad:(UIWebView *)webView
{
    self.alert = [[UIAlertView alloc] initWithTitle:@"Loading..." message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [self.alert show];
    
    UIActivityIndicatorView *aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    aiv.center = CGPointMake(self.alert.bounds.size.width/2, self.alert.bounds.size.height/2);
    [aiv startAnimating];
    [self.alert addSubview:aiv];
}

- (void)dealloc {
    [_webView release];
    [_url release];
    [_txtUrl release];
    [_alert release];
    [super dealloc];
}
- (IBAction)GoClick:(id)sender {
    [self.txtUrl resignFirstResponder];
    if (self.txtUrl.text != nil) {
        self.url = [NSURL URLWithString:self.txtUrl.text];
        [self pageLoad1:self.url];
    }
    else
    {
        self.alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"地址不能为空" delegate:self cancelButtonTitle:@"OK"otherButtonTitles: nil];
        [self.alert show];
    }
}
- (IBAction)resignBoardClick:(id)sender {
    [self.txtUrl resignFirstResponder];
}
@end

xib:


效果图:

请求网络的加载效果:


请求结束的效果图:


2.根据URL地址请求网络图片并且显示出来

PicViewController.h:

//
//  PicViewController.h
//  地图+网络
//
//  Created by 丁小未 on 13-8-27.
//  Copyright (c) 2013年 dingxiaowei. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface PicViewController : UIViewController<UIWebViewDelegate,NSURLConnectionDataDelegate>

@property(nonatomic,retain)NSURL *url;
@property (retain, nonatomic) IBOutlet UIWebView *webView;
@property (retain, nonatomic) NSMutableData * data;
@property (retain, nonatomic) NSURLConnection * connection; 
@end

PicViewController.m:

//
//  PicViewController.m
//  地图+网络
//
//  Created by 丁小未 on 13-8-27.
//  Copyright (c) 2013年 dingxiaowei. All rights reserved.
//

#import "PicViewController.h"

@interface PicViewController ()

@end

@implementation PicViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *urlString =@"http://e.hiphotos.baidu.com/album/w%3D2048/sign=76d548844afbfbeddc59317f4cc8f636/267f9e2f07082838334a05afb999a9014d08f1c2.jpg";
    self.url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:self.url];
    [self.webView loadRequest:request];
    
    //step3:创建链接
    
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    if(self.connection)
        
    {
        
        NSLog(@"创建链接成功");
        
    }else{
        
        NSLog(@"创建链接失败");
        
    }
    
    
    [urlString release];
}

//获取数据

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{
    
    
    NSMutableData * data = [[NSMutableData alloc] init];
    
    self.data = data;
    
    [data release];
    
}

//不断的获取数据

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{
    
    //接受返回数据,这个方法可能会被调用多次,因此将多次返回数据加起来
    
    NSInteger datalength = [data length];
    
    NSLog(@"返回数据量:%d",datalength);
    
    [self.data appendData:data];
    
}

//获取文件地址

-(NSString *)dataFilePath:(NSString*)fileName

{
    
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    NSString *document=[paths objectAtIndex:0];
    
    return [document stringByAppendingPathComponent:fileName];
    
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{ 
    //可以下载图片
    [self.data writeToFile:[self dataFilePath:@"image.jpg"] atomically:YES];
    self.webView.hidden = YES;
    //将沙盒中的图片加载到界面中
    NSString *path = [self dataFilePath:@"image.jpg"];
    UIImage *imag = [[UIImage alloc] initWithContentsOfFile:path];
    UIImageView *img = [[UIImageView alloc] initWithImage:imag];
    CGRect rect = CGRectMake(0, 0, 320,460);
    img.frame = rect;
    [self.view addSubview:img];
}


-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{
    
    NSLog(@"连接失败");
    
}

- (void)dealloc {
    [_webView release];
    [super dealloc];
}
@end


xib:


请求后的效果图:


3.请求天气预报的接口然后json解析请求后的数据并且保存到本地显示出来

WeatherViewController.h:

//
//  WeatherViewController.h
//  地图+网络
//
//  Created by 丁小未 on 13-8-27.
//  Copyright (c) 2013年 dingxiaowei. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface WeatherViewController : UIViewController<UIWebViewDelegate,NSURLConnectionDataDelegate>
@property (retain, nonatomic) IBOutlet UITextField *txtCity;
@property (retain, nonatomic) IBOutlet UITextField *txtMaxTem;
@property (retain, nonatomic) IBOutlet UITextField *txtMinTem;
@property (retain, nonatomic) IBOutlet UITextField *txtTempreture;
@property(retain,nonatomic)NSMutableData *data;
@property (retain, nonatomic) IBOutlet UILabel *label;
@property(retain,nonatomic)NSURLConnection *connection;
- (IBAction)resignBoard:(id)sender;

@end

WeatherViewController.m:

//
//  WeatherViewController.m
//  地图+网络
//
//  Created by 丁小未 on 13-8-27.
//  Copyright (c) 2013年 dingxiaowei. All rights reserved.
//

#import "WeatherViewController.h"

@interface WeatherViewController ()

@end

@implementation WeatherViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.label.text = @"正在请求数据";
    NSString *urlString = @"http://www.weather.com.cn/data/cityinfo/101020100.html";
    NSURL *url = [NSURL URLWithString:urlString];
    //实例化一个request
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    //创建连接
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (self.connection) {
        NSLog(@"创建连接成功");
    }
    else
    {
        NSLog(@"创建连接失败");
    }
    [url release];
    [urlString release];
}

//获取数据

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{
    
    //接受一个服务端回话,再次一般初始化接受数据的对象
    
    //NSLog(@"返回数据类型%@",[response ]);
    
    //NSLog(@"返回数据编码%@",[response text]);
    
    NSMutableData * data = [[NSMutableData alloc] init];
    
    self.data = data;
    
    [data release];
    
}

//不断的获取数据

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{
    
    //接受返回数据,这个方法可能会被调用多次,因此将多次返回数据加起来
    
    NSInteger datalength = [data length];
    
    NSLog(@"返回数据量:%d",datalength);
    
    [self.data appendData:data];
    
}

//获取文件地址

-(NSString *)dataFilePath:(NSString*)fileName

{
    
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    NSString *document=[paths objectAtIndex:0];
    
    return [document stringByAppendingPathComponent:fileName];
    
}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{
    
   //连接结束
    
    NSLog(@"%d",[self.data length]);
    
    self.label.text =@"天气预报";
    
    //可以下载图片
    
    //[self.data writeToFile:[self dataFilePath:@"image.jpg"] atomically:YES];
    
    
    
//    NSString * mystr = [[NSStringalloc] initWithData:self.dataencoding:NSUTF8StringEncoding];
//    
//    [mystr writeToFile:[selfdataFilePath:@"百度图片—全球最大中文图片库.html"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
//    
//    NSLog(@"最后的结果%@",mystr);
//    
//    [mystr release];
    
        NSDictionary *weather = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers  error:nil];
    
        NSLog(@"%@",weather);
    
        [weather writeToFile:[self dataFilePath:@"weather.plist"] atomically:YES];
    
    NSLog(@"%@",[weather allKeys]);
    NSDictionary *dic = [weather objectForKey:@"weatherinfo"];
    NSLog(@"%@",dic);
    
    self.txtCity.text = [dic objectForKey:@"city"];
    self.txtTempreture.text = [dic objectForKey:@"weather"];
    self.txtMaxTem.text = [dic objectForKey:@"temp2"];
    self.txtMinTem.text = [dic objectForKey:@"temp1"];
}


-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{
    
    self.label.text =@"连接失败";
    
}

- (void)dealloc {
    [_txtCity release];
    [_txtMaxTem release];
    [_txtMinTem release];
    [_txtTempreture release];
    [_label release];
    [super dealloc];
}
- (IBAction)resignBoard:(id)sender {
    [self.txtMaxTem resignFirstResponder];
    [self.txtMinTem resignFirstResponder];
    [self.txtCity resignFirstResponder];
    [self.txtTempreture resignFirstResponder];
}
@end

xib:


请求网络后的效果图:


Demo源文件下载(猛戳)

相关文章
|
2月前
|
XML 存储 JSON
Twaver-HTML5基础学习(19)数据容器(2)_数据序列化_XML、Json
本文介绍了Twaver HTML5中的数据序列化,包括XML和JSON格式的序列化与反序列化方法。文章通过示例代码展示了如何将DataBox中的数据序列化为XML和JSON字符串,以及如何从这些字符串中反序列化数据,重建DataBox中的对象。此外,还提到了用户自定义属性的序列化注册方法。
43 1
|
14天前
|
数据采集 JSON 数据处理
抓取和分析JSON数据:使用Python构建数据处理管道
在大数据时代,电商网站如亚马逊、京东等成为数据采集的重要来源。本文介绍如何使用Python结合代理IP、多线程等技术,高效、隐秘地抓取并处理电商网站的JSON数据。通过爬虫代理服务,模拟真实用户行为,提升抓取效率和稳定性。示例代码展示了如何抓取亚马逊商品信息并进行解析。
抓取和分析JSON数据:使用Python构建数据处理管道
|
3天前
|
JSON 缓存 前端开发
PHP如何高效地处理JSON数据:从编码到解码
在现代Web开发中,JSON已成为数据交换的标准格式。本文探讨了PHP如何高效处理JSON数据,包括编码和解码的过程。通过简化数据结构、使用优化选项、缓存机制及合理设置解码参数等方法,可以显著提升JSON处理的性能,确保系统快速稳定运行。
|
18天前
|
JSON JavaScript Java
在Java中处理JSON数据:Jackson与Gson库比较
本文介绍了JSON数据交换格式及其在Java中的应用,重点探讨了两个强大的JSON处理库——Jackson和Gson。文章详细讲解了Jackson库的核心功能,包括数据绑定、流式API和树模型,并通过示例演示了如何使用Jackson进行JSON解析和生成。最后,作者分享了一些实用的代码片段和使用技巧,帮助读者更好地理解和应用这些工具。
在Java中处理JSON数据:Jackson与Gson库比较
|
25天前
|
JSON API 数据格式
postman如何发送json请求其中file字段是一个图片
postman如何发送json请求其中file字段是一个图片
85 4
|
28天前
|
JSON JavaScript API
(API接口系列)商品详情数据封装接口json数据格式分析
在成长的路上,我们都是同行者。这篇关于商品详情API接口的文章,希望能帮助到您。期待与您继续分享更多API接口的知识,请记得关注Anzexi58哦!
|
30天前
|
JSON 前端开发 Java
【Spring】“请求“ 之传递 JSON 数据
【Spring】“请求“ 之传递 JSON 数据
83 2
|
2月前
|
存储 JSON Go
在Gin框架中优雅地处理HTTP请求体中的JSON数据
在Gin框架中优雅地处理HTTP请求体中的JSON数据
|
2月前
|
JSON JavaScript 数据格式
vue写入json数据到文本中+vue引入cdn的用法
vue写入json数据到文本中+vue引入cdn的用法
53 10
|
20天前
|
JSON API 数据格式
商品详情数据JSON格式示例参考(api接口)
JSON数据格式的商品详情数据通常包含商品的多个层级信息,以下是一个综合多个来源信息的JSON数据格式的商品详情数据示例参考: