0

Sorry for my English I'll do my best. I have an issue trying to upload photos from the user's library. First, I get user's photo with this method

func grabPhotos(){


    let imgManager = PHImageManager.defaultManager()

    let requestOptions = PHImageRequestOptions()
    requestOptions.synchronous = false
    requestOptions.deliveryMode = .FastFormat

    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

    if let fetchResult : PHFetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions){

        if fetchResult.count > 0{      

            for i in 0..<fetchResult.count{

                let asset =  fetchResult.objectAtIndex(i) as! PHAsset

                if NSComparisonResult.OrderedSame == asset.creationDate!.compare(self.appDelegate.dateLastUpload!){
                    print("meme date")
                }
                else if NSComparisonResult.OrderedAscending == asset.creationDate!.compare(self.appDelegate.dateLastUpload!){

                }

                else {

                    imgManager.requestImageDataForAsset(asset, options: requestOptions, resultHandler: { (data, string, orientation, objects) in

                        self.Upload((UIImage(data: data!)?.CGImage)! , nomImage: "\(asset.creationDate)" )
                    })
                }
            }

        }

        else{

            print("you got no photos")
        }
    }


}

as you can see, each time I get a photo I want to upload it to my server. the upload part works well.

Here is the upload method

func clickUpload(image:CGImage,nomImage : String){



    let url = NSURL(string: "http://192.168.1.20:1993/upload")

    let image_photo = UIImage(CGImage: image)

    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "POST"

    let boundary = generateBoundaryString()

    //define the multipart request type

    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


    if var image_data = UIImageJPEGRepresentation(image_photo,0.8){

        let body = NSMutableData()

        let fname = nomImage
        let mimetype = "image/jpg"

        //define the data post parameter

        body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Disposition:multipart/form-data; name=\"test\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("enctype=\"multipart/form-data".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("hi\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

        body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData(image_data)
        body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


        body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


        //request.setValue("multipart/form-data", forHTTPHeaderField: "content-Type")
        request.HTTPBody = body

        let session = NSURLSession.sharedSession()

        let task = session.dataTaskWithRequest(request) {
            (
            let data, let response, let error) in

            guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
                print("error")
                return
            }

            let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print(dataString)


        }
        task.resume()
    }
    else {
        print(« data nil")
    }
}

Now problems come... It works well if I upload photos with reduced size, but I want to upload them in HighQualityFormat. I got 170 photos on my device, and it uploads approximatively 80 photos before crashing with this message

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'NSAllocateMemoryPages(1504802) failed'

Could you guys help me to solve it or give me another way to achieve this?

Thank you all.

gkmohit
  • 690
  • 2
  • 12
  • 28
Mat Grlt
  • 131
  • 8
  • You should check out trying to use `autoreleasepool`. Check out this post: http://stackoverflow.com/questions/25860942/is-it-necessary-to-use-autoreleasepool-in-a-swift-program – random Sep 06 '16 at 17:47
  • I tried with autoreleasepool but didn't work... Looks like the problem is that too many UIJPEGRepresentation are called at the same time and memory can't handle it.. – Mat Grlt Sep 07 '16 at 01:04
  • I would also try moving all the upload implementation to a `NSOperation` subclass. This will let the system do some memory management for you – random Sep 07 '16 at 14:01

0 Answers0