【问题标题】:Cannot convert value of type 'String' to expected argument type 'URL'无法将“字符串”类型的值转换为预期的参数类型“URL”
【发布时间】:2016-12-07 06:24:47
【问题描述】:

我正在尝试在我的 iOS 应用中将图片发布到 Instagram。我已经使用了这篇文章中的代码。

Post UIImage to Instagram using Swift similar to SLComposeViewController

我需要换行:

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

到:

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

对于 Swift 3,但随后出现错误:

无法将“字符串”类型的值转换为预期的参数类型“URL”

有人知道如何解决这个问题吗?

谢谢。

【问题讨论】:

  • 你传递的是字符串而不是 URL。
  • 什么是jpgPath

标签: ios swift3 xcode8 nsurl


【解决方案1】:

您将 string 作为参数传递给 write 函数,这是无效参数,因为 write 函数将 URL 作为参数。

所以简单替换

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

用这个:

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

更多详情请查看this

【讨论】:

  • 您的意思是developer.apple.com/reference/foundation/nsdata/1410595-write 吗? (您的链接描述了write(toFile:options:) func)
  • @ŁukaszPrzytuła 谢谢你的指点。我已经替换了链接。
  • 不管怎样,你链接的那个仍然有用(你不必用字符串初始化 URL,只需将字符串作为参数传递)
  • @VishalSonawane 当我按照您的建议进行操作时,我收到错误“调用可以抛出,但它没有标有 'try' 并且错误未处理”。我已将您的建议与以下 Wolverine 的建议结合起来,它让我通过了错误。非常感谢。
【解决方案2】:

试试这个。

let jpegData = UIImageJPEGRepresentation(imageInstagram, 1.0)

我认为“jpgPath”是您尝试保存图像的路径。

如果不是,那么这里是一个示例,您应该如何创建 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)
}

如果 jpgPathString (在你的情况下),你可以这样尝试。

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

【讨论】:

    猜你喜欢
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多