将图像从iOS应用程序发送到服务器的正确方法

时间:2016-07-22 05:55:27

标签: ios swift uiimage

我从相机捕捉图像并将图像转换为base64格式。将图像发送到服务器需要更多时间。如果没有互联网连接,我将它存储到本地数据库,一旦我上网,我想发送多个图像到服务器。从app发送图像到服务器的最佳方法是什么。

2 个答案:

答案 0 :(得分:1)

你有没有试过Alamofire?它支持文件上传。

以下是图片加载的示例:

public func requestImage(url: String) -> SignalProducer<UIImage, NetworkError> {
        return SignalProducer { observer, disposable in
            let serializer = Alamofire.Request.dataResponseSerializer()
            Alamofire.request(.GET, url)
                .response(queue: self.queue, responseSerializer: serializer) {
                    response in
                    switch response.result {
                    case .Success(let data):
                        guard let image = UIImage(data: data) else {
                            observer.sendFailed(.IncorrectDataReturned)
                            return
                        }
                        observer.sendNext(image)
                        observer.sendCompleted()
                    case .Failure(let error):
                        observer.sendFailed(NetworkError(error: error))
                    }
            }
        }
    }

这是async image load的一个例子。

答案 1 :(得分:-1)

您可以按如下方式请求multipart,然后在NSURLSession

中使用该请求
 NSString *boundary = [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]];

        // configure the request
    NSString *urlString = YOUR_URL;
    NSURL *url =[NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"POST"];
    // set content type
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];

    //create body
    request.HTTPBody = [self createBodyWithParameters:params paths:@[filePath] fieldName:fieldName boundary:boundary]; //params(NSDictionary) WILL BE YOUR PARAMETERS TO WEB SERVICE

    [request setValue:[NSString stringWithFormat:@"%lu",(long)[request.HTTPBody length]] forHTTPHeaderField:@"Content-Lenght"];