iOS NSURLSession 관련
6001 단어 NSURLSession
#define DATA(X) [X dataUsingEncoding:NSUTF8StringEncoding]
#define kBoundary @"------------0x0x0x0x0x0x0x0x"
#define IMAGE_CONTENT @"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r
Content-Type: image/jpeg\r
\r
"
#define STRING_CONTENT @"Content-Disposition: form-data; name=\"%@\"\r
\r
"
#define MULTIPART @"multipart/form-data; boundary=------------0x0x0x0x0x0x0x0x"
2. 인터페이스 루트 경로
NSString *kAFAppNetworkAPIBaseURLString = @"http://192.168.1.254:80/pmb/";
3. 그림이나 인터페이스 파라미터 포장
- (NSData *)prepareDataForUpload:(NSDictionary*)dict {
NSArray *keys = [dict allKeys];
NSMutableData *result = [NSMutableData data];
for (int i = 0; i < [keys count]; i++) {
id value = dict[keys[i]];
[result appendData:[[NSString stringWithFormat:@"--%@\r
", kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
if ([value isKindOfClass:[NSData class]]) {
// handle image data
NSString *formstring = [NSString stringWithFormat:IMAGE_CONTENT, keys[i], dict[@"fileName"]];
[result appendData: DATA(formstring)];
[result appendData:value];
} else {
// all non-image fields assumed to be strings
NSString *formstring = [NSString stringWithFormat:STRING_CONTENT, keys[i]];
[result appendData: DATA(formstring)];
[result appendData:DATA(value)];
}
NSString *formstring = @"\r
";
[result appendData:DATA(formstring)];
}
NSString *formstring =[NSString stringWithFormat:@"--%@--\r
", kBoundary];
[result appendData:DATA(formstring)];
return result;
}
4. 업로드
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self uploadFileDict:@{@"user_id":@"44", @"file":UIImagePNGRepresentation([UIImage imageNamed:@"icon41"]), @"fileName":@"icon41.png"} toUrlString:[NSString stringWithFormat:@"%@uploadPhoto", kAFAppNetworkAPIBaseURLString]];
}
- (void)uploadFileDict:(NSDictionary *)dict toUrlString:(NSString *)urlString {
NSData *postData = [self prepareDataForUpload:dict];
NSLog(@"#####################################################
");
NSLog(@"post:%@", postData);//[[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]);
NSLog(@"#####################################################
");
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod: @"POST"];
[urlRequest setValue:MULTIPART forHTTPHeaderField: @"Content-Type"];
//[urlRequest setHTTPBody:postData];// session data , session request body
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
#if 1
[[session uploadTaskWithRequest:urlRequest fromData:postData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@", response);
NSString *outstring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"
1server return message:%@
", outstring);
}] resume];
#else
[[session dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@", response);
NSString *outstring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"
2server return message:%@
", outstring);
}] resume];
#endif
}
5. 요청 인터페이스
//
- (void)changeName:(NSString *)name {
[self normalDicPost:@{@"user_id":@"55", @"nickname":name} action:@"uploadUserInfo" selector:@selector(changeName:)];
}
- (void)normalDicPost:(NSDictionary *)param action:(NSString *)path selector:(SEL)sel {
// 1
NSString *paramStr = @"";
for (NSString *key in param) {
paramStr = [NSString stringWithFormat:@"%@&%@=%@", paramStr, key, param[key]];
}
paramStr = [paramStr substringFromIndex:1];
NSData *paramData = [paramStr dataUsingEncoding:NSUTF8StringEncoding];
// 2
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", kAFAppNetworkAPIBaseURLString, path]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: @"POST"];
[request setHTTPBody:paramData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//NSString *outstring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(@"server return message:%@
%@", outstring, response);
//3 work
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *printStr = @"{
";
for (NSString *key in dic) {
printStr = [NSString stringWithFormat:@"%@ %@ = %@
", printStr, key, dic[key]];
}
NSLog(@" %@} %@
", printStr, [NSThread currentThread]);
// sel
}] resume];
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
iOS NSURLSession 에서 HTTP 요청 하기잘못 처리 되 지 않 았 고, 강하 결합 디자인, 인터페이스 다단 계 패 키 징 등 디자인 이 없 었 습 니 다. 네 이 티 브 NSURLSession http 요청 은 간단 합 니 다....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.