Search code examples
iosiphonexcodeswiftafnetworking

upload image using AFNetworking in swift ios


I am trying to upload an image to my server using AFNetworking in swift , and I got this error The data couldn’t be read because it isn’t in the correct format.

  let manager = AFHTTPRequestOperationManager()
            let url = "http://path/to/server"
            let URL : NSURL = NSURL(string: url)!
            let req : NSURLRequest = NSURLRequest(URL: URL)
    let fileURL = NSURL(string: "file:///var/mobile/Media/DCIM/102APPLE/IMG_2623.PNG")
            manager.POST( url, parameters: nil,
                constructingBodyWithBlock: { (data: AFMultipartFormData!) in
                    do{
                        _ = try data.appendPartWithFileURL(fileURL!, name: "uploaded_file", fileName: "image.png", mimeType: "image/png")
                    }catch{
                    }
                },
                success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
                    print("\(responseObject)")
                },
                failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
                    print("\(error.localizedDescription)")
            })

any help?!


Solution

  • I'm guessing that you can't use an arbitrary path to a file like that. Try using an image file from your app's bundle to start with, and use a call like NSBundle URLForResourceWithExtension to fetch the file.

    If you want to load a file from the user's camera roll you need to use the appropriate API, not a direct file path. (Direct access to the file system is severely limited by the "app sandbox".)