1

iPhone에서 웹 서비스에 이미지를 게시하려고합니다.webservice를 통해 uiimage를 서버에 업로드하는 중 NSXMLParserErrorDomain 오류가 발생합니다.

NSData *Imagedata; 
Imagedata = UIImagePNGRepresentation(imagee); 
strSoapMsg = [[NSString alloc] initWithFormat: 
        @"<?xml version=\"1.0\" encoding=\"utf-8\"?>" 
        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">" 
        "<soap12:Body>" 
        "<SaveMerchantImageFromIPhone xmlns=\"http://tempuri.org/\">" 
        "<byteArrayImage>%@</byteArrayImage>" 
        "<ProfileID>%d</ProfileID>" 
        "</SaveMerchantImageFromIPhone>" 
        "</soap12:Body>" 
        "</soap12:Envelope>", [NSData dataWithData:Imagedata],merchantProfileID]; 
// strSoapMsg = [[NSString alloc] initWithFormat:@"%@,%d",Imagedata,merchantProfileID]; 
//---print it to the Debugger Console for verification--- 
NSLog(@"soapMsg..........%@",strSoapMsg); 

NSString *str_url = [ NSString stringWithFormat:@"%@user.asmx",xmlWebservicesUrl]; 
NSURL *url = [NSURL URLWithString:str_url]; 
req = [NSMutableURLRequest requestWithURL:url]; 

//---set the headers--- 

NSString *msgLength = [NSString stringWithFormat:@"%d",[strSoapMsg length]]; 
[req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 
[req addValue:@"http://tempuri.org/SaveMerchantImageFromIPhone" forHTTPHeaderField:@"SOAPAction"]; 
[req addValue:msgLength forHTTPHeaderField:@"Content-Length"]; 

//---set the HTTP method and body--- 

[req setHTTPMethod:@"POST"]; 
[req setHTTPBody: [strSoapMsg dataUsingEncoding:NSUTF8StringEncoding]]; 


conn = [[NSURLConnection alloc] initWithRequest:req delegate:self]; 
if (conn) 
{ 
    webSaveMerchantImageFromIphone = [[NSMutableData data] retain]; 
} 

나는 %@ 형식 지정자 개체를 필요하기 때문에 실패 생각 : 내가 해봤 모든 것을 설명 먼저 코드를 게시합니다. 그러나 나는 확실하지 않다.

+0

완전히 새로운 이미지 게시 방법 (일반 웹 서비스 통신)은 얼마나 열려 있습니까? 나는 POST 기반의 웹 서비스를 다루기 쉽게 만드는 클래스를 작성했다. 그것은 무거운 짐을 싣기 위해 AFNetworking을 기반으로하며 사용합니다. 이것이 당신이 관심있는 것이면, 나는 대답으로 게시 할 것입니다. –

+0

예. 나는 항상 새로운 방식으로 관심이 있습니다. 답변을 게시하십시오. – MURR

답변

0

요청이 비동기 적으로 전송되고 응답을 기다리지 않으므로 빈 xml을 파싱하는 중일 수 있습니다.
당신은 당신이받는 데이터와
-(void)connectionDidFinishLoading:(NSURLConnection *)connection 파서을 시작하기를 연결하는 위임 방법
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data를 사용해야합니다.
NSURLConnectionDelegate 프로토콜을 살펴보십시오. https://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/NSURLConnectionDelegate

0

다음은 웹 서비스와 인터페이스하는 방법입니다. 확실히 일을하는 유일한 방법은 아니지만 아마도 가장 인기가 없지만 매우 안전하고 매우 빠릅니다. 첫째로, 나의 웹 서비스는 POST 기반이다. 모든 매개 변수는 크로스 플랫폼 독립성을 제공하는 웹 서비스에 게시됩니다 (PHP와 .NET 기반 웹 서비스 모두 사용함). iOS 앱만 웹 서비스와 통신 할 수 있다는 점에서 보안을 유지하는 모든 웹 서비스 호출과 함께 APIKey를 포함합니다. 또한 APIKey를 변경하고 필요한 경우 사용자가 응용 프로그램의 최신 버전으로 업데이트 할 수있는 기능을 제공합니다 (아직 사용하지 않았지만 사용해야하는 경우에 있습니다.)이 클래스는 AFNetworking에 의존하고 사용합니다. (아이폰 OS 포함 프레임 워크 포함) 네트워크 통신을위한 여러 가지 라이브러리를 사용했으며, AFNetworking을 발견 한 것은 내가 뭐하는 거지에 매우 유용하고 효율적으로 여기

내 클래스의 인터페이스 파일입니다.

/* 
NetworkClient.h 

Created by LJ Wilson on 2/3/12. 
Copyright (c) 2012 LJ Wilson. All rights reserved. 
License: 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
and associated documentation files (the "Software"), to deal in the Software without restriction, 
including without limitation the rights to use, copy, modify, merge, publish, distribute, 
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
furnished to do so, subject to the following conditions: 

The above copyright notice and this permission notice shall be included in all copies or 
substantial portions of the Software. 

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT 
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
*/ 

#import <Foundation/Foundation.h> 

extern NSString * const APIKey; 

@interface NetworkClient : NSObject 

+(void)processURLRequestWithURL:(NSString *)url 
         andParams:(NSDictionary *)params 
          block:(void (^)(id obj))block; 

+(void)processURLRequestWithURL:(NSString *)url 
         andParams:(NSDictionary *)params 
        syncRequest:(BOOL)syncRequest 
          block:(void (^)(id obj))block; 

+(void)processURLRequestWithURL:(NSString *)url 
         andParams:(NSDictionary *)params 
        syncRequest:(BOOL)syncRequest 
      alertUserOnFailure:(BOOL)alertUserOnFailure 
          block:(void (^)(id obj))block; 

+(void)processFileUploadRequestWithURL:(NSString *)url 
          andParams:(NSDictionary *)params 
           fileData:(NSData *)fileData 
           fileName:(NSString *)fileName 
           mimeType:(NSString *)mimeType 
           block:(void (^)(id obj))block; 

+(void)handleNetworkErrorWithError:(NSError *)error; 

+(void)handleNoAccessWithReason:(NSString *)reason; 

@end 

구현 파일 :

/* 
NetworkClient.m 

Created by LJ Wilson on 2/3/12. 
Copyright (c) 2012 LJ Wilson. All rights reserved. 
License: 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
and associated documentation files (the "Software"), to deal in the Software without restriction, 
including without limitation the rights to use, copy, modify, merge, publish, distribute, 
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
furnished to do so, subject to the following conditions: 

The above copyright notice and this permission notice shall be included in all copies or 
substantial portions of the Software. 

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT 
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
*/ 

#import "NetworkClient.h" 
#import "AFHTTPClient.h" 
#import "AFHTTPRequestOperation.h" 
#import "SBJson.h" 

NSString * const APIKey = @"YourAPIKeyGoesHereIfYouChooseToUseIt"; 

@implementation NetworkClient 

+(void)processURLRequestWithURL:(NSString *)url 
         andParams:(NSDictionary *)params 
          block:(void (^)(id obj))block { 

    [self processURLRequestWithURL:url andParams:params syncRequest:NO alertUserOnFailure:NO block:^(id obj) { 
     block(obj); 
    }]; 
} 

+(void)processURLRequestWithURL:(NSString *)url 
         andParams:(NSDictionary *)params 
        syncRequest:(BOOL)syncRequest 
          block:(void (^)(id obj))block { 
    [self processURLRequestWithURL:url andParams:params syncRequest:syncRequest alertUserOnFailure:NO block:^(id obj) { 
     block(obj); 
    }]; 
} 


+(void)processURLRequestWithURL:(NSString *)url 
         andParams:(NSDictionary *)params 
        syncRequest:(BOOL)syncRequest 
      alertUserOnFailure:(BOOL)alertUserOnFailure 
          block:(void (^)(id obj))block { 

    // Default url goes here, pass in a nil to use it 
    if (url == nil) { 
     url = @"DefaultURLGoesHere"; 
    } 

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:params]; 
    [dict setValue:APIKey forKey:@"APIKey"]; 

    NSDictionary *newParams = [[NSDictionary alloc] initWithDictionary:dict]; 

    NSURL *requestURL; 
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:requestURL]; 

    NSMutableURLRequest *theRequest = [httpClient requestWithMethod:@"POST" path:url parameters:newParams]; 

    __block NSString *responseString = @""; 

    AFHTTPRequestOperation *_operation = [[AFHTTPRequestOperation alloc] initWithRequest:theRequest]; 
    __weak AFHTTPRequestOperation *operation = _operation; 

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
     responseString = [operation responseString]; 

     id retObj = [responseString JSONValue]; 

     // Check for invalid response (No Access) 
     if ([retObj isKindOfClass:[NSDictionary class]]) { 
      if ([[(NSDictionary *)retObj valueForKey:@"Message"] isEqualToString:@"No Access"]) { 
       block(nil); 
       [self handleNoAccessWithReason:[(NSDictionary *)retObj valueForKey:@"Reason"]]; 
      } 
     } else if ([retObj isKindOfClass:[NSArray class]]) { 
      if ([(NSArray *)retObj count] > 0) { 
       NSDictionary *dict = [(NSArray *)retObj objectAtIndex:0]; 
       if ([[dict valueForKey:@"Message"] isEqualToString:@"No Access"]) { 
        block(nil); 
        [self handleNoAccessWithReason:[(NSDictionary *)retObj valueForKey:@"Reason"]]; 
       } 
      } 
     } 
     block(retObj); 
    } 
             failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
              NSLog(@"Failed with error = %@", [NSString stringWithFormat:@"[Error]:%@",error]); 
              block(nil); 
              if (alertUserOnFailure) { 
               // Let the user know something went wrong 
               [self handleNetworkErrorWithError:operation.error]; 
              } 

             }]; 

    [operation start]; 

    if (syncRequest) { 
     // Process the request syncronously 
     [operation waitUntilFinished]; 
    } 


} 


#pragma mark - processFileUpload 
+(void)processFileUploadRequestWithURL:(NSString *)url 
          andParams:(NSDictionary *)params 
           fileData:(NSData *)fileData 
           fileName:(NSString *)fileName 
           mimeType:(NSString *)mimeType 
           block:(void (^)(id obj))block { 

    // Default url goes here, pass in a nil to use it 
    if (url == nil) { 
     url = @"DefaultURLGoesHere"; 
    } 

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:params]; 
    [dict setValue:APIKey forKey:@"APIKey"]; 

    NSDictionary *newParams = [[NSDictionary alloc] initWithDictionary:dict]; 
    AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:url]]; 

    NSMutableURLRequest *myRequest = [client multipartFormRequestWithMethod:@"POST" 
                     path:@"" 
                   parameters:newParams 
                constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) { 
     [formData appendPartWithFileData:fileData name:fileName fileName:fileName mimeType:mimeType]; 
    }]; 


    AFHTTPRequestOperation *_operation = [[AFHTTPRequestOperation alloc] initWithRequest:myRequest]; 
    __weak AFHTTPRequestOperation *operation = _operation; 
    __block NSString *responseString = @""; 

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
     responseString = [operation responseString]; 

     id retObj = [responseString JSONValue]; 

     // Check for invalid response (No Access) 
     if ([retObj isKindOfClass:[NSDictionary class]]) { 
      if ([[(NSDictionary *)retObj valueForKey:@"Message"] isEqualToString:@"No Access"]) { 
       block(nil); 
       [self handleNoAccessWithReason:[(NSDictionary *)retObj valueForKey:@"Reason"]]; 
      } 
     } else if ([retObj isKindOfClass:[NSArray class]]) { 
      if ([(NSArray *)retObj count] > 0) { 
       NSDictionary *dict = [(NSArray *)retObj objectAtIndex:0]; 
       if ([[dict valueForKey:@"Message"] isEqualToString:@"No Access"]) { 
        block(nil); 
        [self handleNoAccessWithReason:[(NSDictionary *)retObj valueForKey:@"Reason"]]; 
       } 
      } 
     } 
     block(retObj); 


    } 
             failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
              NSLog(@"Failed with error = %@", [NSString stringWithFormat:@"[Error]:%@",error]); 
              block(nil); 
             }]; 

    [operation start]; 


} 


#pragma mark - Error and Access Handling 
+(void)handleNetworkErrorWithError:(NSError *)error { 
    NSString *errorString = [NSString stringWithFormat:@"[Error]:%@",error]; 

    // Standard UIAlert Syntax 
    UIAlertView *myAlert = [[UIAlertView alloc] 
          initWithTitle:@"Connection Error" 
          message:errorString 
          delegate:nil 
          cancelButtonTitle:@"OK" 
          otherButtonTitles:nil, nil]; 

    [myAlert show]; 

} 

+(void)handleNoAccessWithReason:(NSString *)reason { 
    // Standard UIAlert Syntax 
    UIAlertView *myAlert = [[UIAlertView alloc] 
          initWithTitle:@"No Access" 
          message:reason 
          delegate:nil 
          cancelButtonTitle:@"OK" 
          otherButtonTitles:nil, nil]; 

    [myAlert show]; 

} 


@end 

그리고 샘플 전화 :

UIImage *image = [UIImage [email protected]"MyImage.png"]; 
NSData *imageData = UIImagePNGRepresentation(image); 
NSString *filename = @"MyImage.png"; 

params = [NSDictionary dictionaryWithObjectsAndKeys: 
           @"Param1Value", @"Param1Name", 
           fileName, @"Filename", 
           nil]; 

[NetworkClient processFileUploadRequestWithURL:nil 
            andParams:params 
             fileData:imageData 
             fileName:fileName 
             mimeType:@"image/png" 
              block:^(id obj) { 
    // Do something 
}]; 

질문이 있으면 알려주세요.

관련 문제