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

简介:

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

-(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源文件下载(猛戳)














本文转蓬莱仙羽51CTO博客,原文链接:http://blog.51cto.com/dingxiaowei/1366414,如需转载请自行联系原作者
相关文章
|
开发框架 前端开发 Android开发
Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势
本文深入探讨了 Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势。这对于实现高效的跨平台移动应用开发具有重要指导意义。
1795 4
|
JavaScript 前端开发 Android开发
【03】仿站技术之python技术,看完学会再也不用去购买收费工具了-修改整体页面做好安卓下载发给客户-并且开始提交网站公安备案-作为APP下载落地页文娱产品一定要备案-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
【03】仿站技术之python技术,看完学会再也不用去购买收费工具了-修改整体页面做好安卓下载发给客户-并且开始提交网站公安备案-作为APP下载落地页文娱产品一定要备案-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
807 13
【03】仿站技术之python技术,看完学会再也不用去购买收费工具了-修改整体页面做好安卓下载发给客户-并且开始提交网站公安备案-作为APP下载落地页文娱产品一定要备案-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
|
安全 Linux 虚拟化
Cisco IOS XRv 9000 Router IOS XR Release 7.11.2 MD - 思科 IOS XR 网络操作系统
Cisco IOS XRv 9000 Router IOS XR Release 7.11.2 MD - 思科 IOS XR 网络操作系统
879 3
Cisco IOS XRv 9000 Router IOS XR Release 7.11.2 MD - 思科 IOS XR 网络操作系统
|
关系型数据库 MySQL 数据库
实时计算 Flink版操作报错合集之网络缓冲池(NetworkBufferPool)中可用内存不足,该如何解决
在使用实时计算Flink版过程中,可能会遇到各种错误,了解这些错误的原因及解决方法对于高效排错至关重要。针对具体问题,查看Flink的日志是关键,它们通常会提供更详细的错误信息和堆栈跟踪,有助于定位问题。此外,Flink社区文档和官方论坛也是寻求帮助的好去处。以下是一些常见的操作报错及其可能的原因与解决策略。
|
JavaScript 搜索推荐 Android开发
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
824 8
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
|
数据采集 JavaScript Android开发
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
938 7
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
|
iOS开发 开发者
iOS平台RTMP|RTSP播放器如何实时回调YUV数据
我们在做RTMP、RTSP播放器的时候,有开发者需要自己处理拉取到的YUV数据,做二次分析之用,为此,我们做了以下的设计:InitPlayer之后,再调用SmartPlayerStart()接口之前,设置yuv数据回调即可。
417 6
|
缓存
Flutter Image从网络加载图片刷新、强制重新渲染
Flutter Image从网络加载图片刷新、强制重新渲染
809 1
|
机器学习/深度学习 Serverless 文件存储
函数计算操作报错合集之在网络设置完成后进行挂载的指令,报错:找不到网络路径,该如何处理
在使用函数计算服务(如阿里云函数计算)时,用户可能会遇到多种错误场景。以下是一些常见的操作报错及其可能的原因和解决方法,包括但不限于:1. 函数部署失败、2. 函数执行超时、3. 资源不足错误、4. 权限与访问错误、5. 依赖问题、6. 网络配置错误、7. 触发器配置错误、8. 日志与监控问题。
405 2
|
缓存 NoSQL Redis
redis管道操作(节省网络IO开销)
pipeline中发送的每个command都会被server立即执行,如果执行失败,将会在此后的响应中得到信息;也就是pipeline并不是表达“所有command都一起成功”的语义,管道中前面命令失败,后面命令不会有影响,继续执行。
359 1

热门文章

最新文章