从远程下载图片到UIImage(认证等复杂方法)

 从远程下载图片到UIImage,然后再180度转换图片

 1 #import <Foundation/Foundation.h>
2 #define TIMEOUT_SEC 20.0
3
4 @interface TSHttpClient : NSObject {
5 NSURLConnection *connection;
6 NSMutableData *recievedData;
7 int statusCode;
8 BOOL contentTypeIsXml;
9
10 int rate_limit;
11 int rate_limit_remaining;
12 NSDate *rate_limit_reset;
13 }
14
15 - (void)requestGET:(NSString*)url;
16 - (void)requestPOST:(NSString*)url body:(NSString*)body;
17 - (void)requestGET:(NSString*)url username:(NSString*)username password:(NSString*)password;
18 - (void)requestPOST:(NSString*)url body:(NSString*)body username:(NSString*)username password:(NSString*)password;
19
20 - (void)cancel;
21
22 - (void)requestSucceeded;
23 - (void)requestFailed:(NSError*)error;
24
25 - (void)reset;
26
27 @property (readonly) NSMutableData *recievedData;
28 @property (readonly) int statusCode;
29
30 @end

 

  1 #import "TSHttpClient.h"
2
3 @implementation TSHttpClient
4
5 @synthesize recievedData, statusCode;
6
7 - (id)init {
8 if (self = [super init]) {
9 [self reset];
10 }
11 return self;
12 }
13
14 - (void)dealloc {
15 NSLog(@"NTLNHttpClient#dealloc");
16 [connection release];
17 [recievedData release];
18 [rate_limit_reset release];
19 [super dealloc];
20 }
21
22 + (NSString*)stringEncodedWithBase64:(NSString*)str
23 {
24 static const char *tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
25
26 const char *s = [str UTF8String];
27 int length = [str length];
28 char *tmp = malloc(length * 4 / 3 + 4);
29
30 int i = 0;
31 int n = 0;
32 char *p = tmp;
33
34 while (i < length) {
35 n = s[i++];
36 n *= 256;
37 if (i < length) n += s[i];
38 i++;
39 n *= 256;
40 if (i < length) n += s[i];
41 i++;
42
43 p[0] = tbl[((n & 0x00fc0000) >> 18)];
44 p[1] = tbl[((n & 0x0003f000) >> 12)];
45 p[2] = tbl[((n & 0x00000fc0) >> 6)];
46 p[3] = tbl[((n & 0x0000003f) >> 0)];
47
48 if (i > length) p[3] = '=';
49 if (i > length + 1) p[2] = '=';
50
51 p += 4;
52 }
53
54 *p = '\0';
55
56 NSString *ret = [NSString stringWithCString:tmp];
57 free(tmp);
58
59 return ret;
60 }
61
62 + (NSString*) stringOfAuthorizationHeaderWithUsername:(NSString*)username password:(NSString*)password {
63 return [@"Basic " stringByAppendingString:[TSHttpClient stringEncodedWithBase64:
64 [NSString stringWithFormat:@"%@:%@", username, password]]];
65 }
66
67 - (NSMutableURLRequest*)makeRequest:(NSString*)url {
68 NSString *encodedUrl = (NSString*)CFURLCreateStringByAddingPercentEscapes(
69 NULL, (CFStringRef)url, NULL, NULL, kCFStringEncodingUTF8);
70 NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
71 [request setURL:[NSURL URLWithString:encodedUrl]];
72 [request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
73 [request setTimeoutInterval:TIMEOUT_SEC];
74 [request setHTTPShouldHandleCookies:FALSE];
75 [encodedUrl release];
76 return request;
77 }
78
79 - (NSMutableURLRequest*)makeRequest:(NSString*)url username:(NSString*)username password:(NSString*)password {
80 NSMutableURLRequest *request = [self makeRequest:url];
81 [request setValue:[TSHttpClient stringOfAuthorizationHeaderWithUsername:username password:password]
82 forHTTPHeaderField:@"Authorization"];
83 return request;
84 }
85
86 - (void)reset {
87 [recievedData release];
88 recievedData = [[NSMutableData alloc] init];
89 [connection release];
90 connection = nil;
91 [rate_limit_reset release];
92 rate_limit_reset = nil;
93
94 statusCode = 0;
95 contentTypeIsXml = NO;
96
97 rate_limit = 0;
98 rate_limit_remaining = 0;
99 }
100
101 - (void)prepareWithRequest:(NSMutableURLRequest*)request {
102 // do nothing (for OAuthHttpClient)
103 }
104
105 - (void)requestGET:(NSString*)url {
106 [self reset];
107 NSMutableURLRequest *request = [self makeRequest:url];
108 [self prepareWithRequest:request];
109 connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
110 }
111
112 - (void)requestPOST:(NSString*)url body:(NSString*)body {
113 [self reset];
114 NSMutableURLRequest *request = [self makeRequest:url];
115 [request setHTTPMethod:@"POST"];
116 if (body) {
117 [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
118 }
119 [self prepareWithRequest:request];
120 connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
121 }
122
123 - (void)requestGET:(NSString*)url username:(NSString*)username password:(NSString*)password {
124 [self reset];
125 NSMutableURLRequest *request = [self makeRequest:url username:username password:password];
126 connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
127 }
128
129 - (void)requestPOST:(NSString*)url body:(NSString*)body username:(NSString*)username password:(NSString*)password {
130 [self reset];
131 NSMutableURLRequest *request = [self makeRequest:url username:username password:password];
132 [request setHTTPMethod:@"POST"];
133 if (body) {
134 [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
135 }
136 connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
137 }
138
139 - (void)cancel {
140 [connection cancel];
141 [self reset];
142 [self requestFailed:nil];
143 }
144
145 - (void)requestSucceeded {
146 // implement by subclass
147 }
148
149 - (void)requestFailed:(NSError*)error {
150 // implement by subclass
151 }
152 /*
153 -(void)connection:(NSURLConnection*)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge {
154 [[challenge sender] cancelAuthenticationChallenge:challenge];
155 }
156 */
157
158 - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
159 return nil;
160 }
161
162 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
163 NSLog(@"didReceiveResponse");
164
165 statusCode = [(NSHTTPURLResponse*)response statusCode];
166 NSDictionary *header = [(NSHTTPURLResponse*)response allHeaderFields];
167
168 contentTypeIsXml = NO;
169 NSString *content_type = [header objectForKey:@"Content-Type"];
170 if (content_type) {
171 NSRange r = [content_type rangeOfString:@"xml"];
172 if (r.location != NSNotFound) {
173 contentTypeIsXml = YES;
174 }
175 }
176
177 for (NSString *s in [header allKeys]) {
178 NSLog(@"header: %@", s);
179 }
180
181 NSString *rateLimit = [header objectForKey:@"X-Ratelimit-Limit"];
182 NSString *rateLimitRemaining = [header objectForKey:@"X-Ratelimit-Remaining"];
183 NSString *rateLimitReset = [header objectForKey:@"X-Ratelimit-Reset"];
184 if (rateLimit && rateLimitRemaining) {
185 rate_limit = [rateLimit intValue];
186 rate_limit_remaining = [rateLimitRemaining intValue];
187 rate_limit_reset = [[NSDate dateWithTimeIntervalSince1970:[rateLimitReset intValue]] retain];
188 NSLog(@"rate_limit: %d rate_limit_remaining:%d",rate_limit, rate_limit_remaining);
189 }
190 }
191
192 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
193 NSLog(@"didReceiveData");
194 [recievedData appendData:data];
195 }
196
197 - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
198 NSLog(@"connectionDidFinishLoading");
199 [self requestSucceeded];
200 [self reset];
201 }
202
203 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError*) error {
204 NSLog(@"didFailWithError");
205 [self requestFailed:error];
206 [self reset];
207 }
208
209 @end

 

 1 #import <Foundation/Foundation.h>
2 #import "TSHttpClient.h"
3
4 @class TSMallClient;
5
6 @protocol TSClientDelegate
7 //请求开始
8 - (void)tsClientBegin:(TSMallClient*)sender;
9 //请求结束
10 - (void)tsClientEnd:(TSMallClient*)sender;
11 //请求成功
12 - (void)tsClientSucceeded:(TSMallClient*)sender messages:(NSArray*)messages;
13 //请求失败
14 - (void)tsClientFailed:(TSMallClient*)sender;
15 @end
16
17 @interface TSMallClient : TSHttpClient
18 {
19 //委托
20 NSObject<TSClientDelegate> *delegate;
21 }
22
23 @property (readwrite, retain) NSObject<TSClientDelegate> *delegate;
24
25 @end

 

 1 #import "TSMallClient.h"
2
3 @implementation TSMallClient
4 @synthesize delegate;
5
6 - (void)requestSucceeded {
7 if (statusCode == 200) {
8 [delegate tsClientSucceeded:self messages:nil];
9 }
10 }
11
12 -(void) dealloc
13 {
14 [delegate release];
15 [super dealloc];
16 }
17
18 @end

 

 1 #import <UIKit/UIKit.h>
2 #import "TSMallClient.h"
3
4 @interface TSImg : UIView
5 {
6 UIImage *img;
7 UIImageView *imgviews;
8 //下载指示器
9 UIActivityIndicatorView *indicator;
10 }
11
12 @end

 

#import "TSImg.h"

@implementation TSImg
#define SizeAcitivityIndicator 20.0

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
img=[UIImage imageNamed:@"none.gif"];

UILabel *lb=[[UILabel alloc]init];
[lb setText:@"加载图片"];
[lb setFrame:CGRectMake(50, 10, 100, 50)];
imgviews=[[UIImageView alloc]initWithFrame:[[UIScreen mainScreen]applicationFrame]];
imgviews.image=img;
imgviews.bounds=CGRectMake(0, 150, 320, 320);

indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//位于imgviews中间
indicator.frame = CGRectMake((imgviews.frame.size.width - SizeAcitivityIndicator) / 2.0, (imgviews.frame.size.height - SizeAcitivityIndicator) / 2.0+150, SizeAcitivityIndicator, SizeAcitivityIndicator);
indicator.hidesWhenStopped = YES;

[imgviews addSubview:indicator];
[indicator startAnimating];

[self addSubview:imgviews];
[self addSubview:lb];
[lb release];
[self downloadImg];
}
return self;
}

//下载图片
-(void) downloadImg
{
TSMallClient *tmc=[[[TSMallClient alloc]init]autorelease];
tmc.delegate=(NSObject<TSClientDelegate>*)self;
[tmc requestGET:@"http://www.yishimai.com/ios/protocol/mountain.jpg"];


}

//下载完成后水平转180度
- (void)tsClientSucceeded:(TSHttpClient*)sender messages:(NSArray*)messages
{

[img release];
img = [[UIImage alloc] initWithData:sender.recievedData];
imgviews.image=img;
[indicator performSelector:@selector(stopAnimating)];

UIViewAnimationTransition trans = UIViewAnimationTransitionFlipFromRight;

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0f];
[UIView setAnimationTransition:trans forView:imgviews cache:YES];
[imgviews exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
[UIView commitAnimations];
}

-(void) dealloc
{
[indicator release];
[imgviews release];
[img release];
[super dealloc];
}

@end








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值