標籤:上傳照片 iosdevtip nsurlconnection nsmutableurlrequest iswifting社區
需求:上傳一張照片和內容,內容包括:使用者編輯的內容、經緯度、地點等等,就是類似發一個說說。這就是一個很平常的功能,實現的方式想必各位能想到很多。
接下來我想用系統的NSURLConnection來實現這個功能:
首先我們要定義一個全域變數:
/** * 請求返回資料 */@property (nonatomic, strong) NSMutableData *mResponseData;
實現代碼:
//字典裡面裝的是你要上傳的內容NSDictionary *parameters = @{@"content": @"這是剛剛線上的官方網站www.superqq.com"};//上傳的介面NSString* urlstring = @"http://superqq.com/";//分界線的標識符NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";//根據url初始化requestNSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstring] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];//分界線 --AaB03xNSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];//結束符 AaB03x--NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];// //要上傳的圖片// UIImage *image=[params objectForKey:@"pic"];//得到圖片的dataNSData *data = UIImagePNGRepresentation(self.image);//http body的字串NSMutableString *body=[[NSMutableString alloc]init];//參數的集合的所有key的集合NSArray *keys= [parameters allKeys];//遍曆keysfor(int i=0;i<[keys count];i++){ //得到當前key NSString *key=[keys objectAtIndex:i]; //如果key不是pic,說明value是字元類型,比如name:Boris if(![key isEqualToString:@"pic"]) { //添加分界線,換行 [body appendFormat:@"%@\r\n",MPboundary]; //添加欄位名稱,換2行 [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key]; //添加欄位的值 [body appendFormat:@"%@\r\n",[parameters objectForKey:key]]; }}////添加分界線,換行[body appendFormat:@"%@\r\n",MPboundary];//聲明pic欄位,檔案名稱為boris.png[body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];//聲明上傳檔案的格式[body appendFormat:@"Content-Type: image/png\r\n\r\n"];//聲明結束符:--AaB03x--NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];//聲明myRequestData,用來放入http bodyNSMutableData *myRequestData=[NSMutableData data];//將body字串轉化為UTF8格式的二進位[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];//將image的data加入[myRequestData appendData:data];//加入結束符--AaB03x--[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];//設定HTTPHeader中Content-Type的值NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];//設定HTTPHeader[request setValue:content forHTTPHeaderField:@"Content-Type"];//設定Content-Length[request setValue:[NSString stringWithFormat:@"%d", (int)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];//設定http body[request setHTTPBody:myRequestData];//http method[request setHTTPMethod:@"POST"];//建立串連,設定代理NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];//設定接受response的dataif (conn) { _mResponseData = [[NSMutableData alloc] init];}
NSURLConnectionDelegate的代理方法:
#pragma mark - NSURLConnectionDelegate- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ [_mResponseData setLength:0];}- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [_mResponseData appendData:data];}- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:_mResponseData options:kNilOptions error:nil]; NSLog(@"%@", dic);}- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ NSLog(@"Error: %@", error);}
這是我的實現方式,再次拋磚引玉,如果你要好的方法,歡迎分享!
我也會將大家分享的方法發到iOS開發公眾帳號:iOSDevTip 裡面,分享給更多iOS開發人員。
NSMutableURLRequest和NSURLConnection用Post方式上傳照片