-4

I am trying to implement posting an image to Instagram in my iOS app. I have used the code in this post.

Post UIImage to Instagram using Swift similar to SLComposeViewController

I need to change the line:

UIImageJPEGRepresentation(imageInstagram, 1.0)!.writeToFile(jpgPath, atomically: true)

to:

UIImageJPEGRepresentation(imageInstagram, 1.0)!.write(jpgPath, options: true)

for Swift 3 but then I get the error:

Cannot convert value of type 'String' to expected argument type 'URL'

Does anybody know how to fix this?

Thanks.

Community
  • 1
  • 1
Humanoid
  • 17
  • 2
  • 3

2 Answers2

2

You are passing string as argument to write function which is invalid argument as write function takes URL as an argument.

So simply replace

UIImageJPEGRepresentation(imageInstagram, 1.0)!.write(jpgPath, options: true)

with this:

UIImageJPEGRepresentation(imageInstagram, 1.0)!.write(to: URL(fileURLWithPath: jpgPath), options: .atomic)

For more details have a look at this

Vishal Sonawane
  • 2,637
  • 2
  • 16
  • 21
  • 1
    Did you mean https://developer.apple.com/reference/foundation/nsdata/1410595-write ? (Your link describes the `write(toFile:options:)` func) – Łukasz Przytuła Dec 07 '16 at 06:56
  • @ŁukaszPrzytuła Thank you for pointing it. I have replaced the link. – Vishal Sonawane Dec 07 '16 at 07:21
  • Anyway, the one you linked to is still useful (you wouldn't have to initialize URL with string, just pass the string as parameter) – Łukasz Przytuła Dec 07 '16 at 07:23
  • @VishalSonawane When I follow your suggestion I get the error "Call can throw, but it is not marked with 'try' and the error is not handled". I have combined your suggestion with Wolverine's below and it has got me passed the error. Thanks very much. – Humanoid Dec 07 '16 at 08:28
1

Try this.

let jpegData = UIImageJPEGRepresentation(imageInstagram, 1.0)

As I consider "jpgPath" is PATH where you are trying to save image.

if not then here is a example how you should create that PATH URL

let jpgPath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("instagram.jpg")

do {
    try jpegData.write(to: jpgPath, options: .atomic)
} catch {
    print(error)
}

If jpgPath is a String (Which is in your case), you can try like this.

do {
    try data.write(to: URL(fileURLWithPath: jpgPath), options: .atomic)
} catch {
    print(error)
}
Wolverine
  • 4,264
  • 1
  • 27
  • 49