将字符串转换为NSURL将返回nil

时间:2016-09-22 03:34:00

标签: ios swift image nsurl

我试图从这样的网址获取图片:

var string = "https://maps.googleapis.com/maps/api/staticmap?key=AIzaSyAJeHxZaZuNsYimNCJ4r0yuO-OYM8cINOI&center=6.241381,-75.595083&zoom=13&size=600x300&path=color:0x0000ff|weight:5|6.241381,-75.595083&signature=u7sM3m2h-qFSJoARR7cqD0CSBvU="

let url = NSURL(string: string.stringByRemovingPercentEncoding!)

if let data = NSData(contentsOfURL: url){
      let image = UIImage(data: data)
}

但它返回 url 。看起来网址并不存在但是如果你去网址你会看到一个图像。

那么演员的问题是什么?或者我怎样才能得到这个图像。

4 个答案:

答案 0 :(得分:2)

这就是我使用AlamofireImage

在我的应用程序中加载图像的方法
let url = NSURL(string:"someUrl")
                self.imgView.af_setImageWithURL(url!, placeholderImage: nil, filter: nil,  imageTransition: .CrossDissolve(0.5), runImageTransitionIfCached: false, completion:  { (error) in
                // do Something when asynchronous image loading is completed
            })

修改 你的网址包含|这对url无效,因此您可以使用PercentEncoding。

这是一个例子

let strurl = "https://maps.googleapis.com/maps/api/staticmap?key=AIzaSyAJeHxZaZuNsYimNCJ4r0yuO-OYM8cINOI&center=6.241381,-75.595083&zoom=13&size=600x300&path=color:0x0000ff|weight:5|6.241381,-75.595083&signature=u7sM3m2h-qFSJoARR7cqD0CSBvU="
let myURL = NSURL(string: strurl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)
self.imgView.af_setImageWithURL(myURL!, placeholderImage: nil, filter: nil,  imageTransition: .CrossDissolve(0.5), runImageTransitionIfCached: false, completion:  { (error) in
            // do Something when asynchronous image loading is completed
        })

答案 1 :(得分:2)

您必须在查询中添加百分比编码,如下所示:

Swift 2.3

let domainAPI = "https://maps.googleapis.com/maps/api/staticmap?"
let query = "key=AIzaSyAJeHxZaZuNsYimNCJ4r0yuO-OYM8cINOI&center=6.241381,-75.595083&zoom=13&size=600x300&path=color:0x0000ff|weight:5|6.241381,-75.595083&signature=u7sM3m2h-qFSJoARR7cqD0CSBvU="
if let queryPercentEncoded = query.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()),
    let url = NSURL(string: domainAPI + queryPercentEncoded) {
    print(url)
}

Swift 3

if let queryPercentEncoded = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
    let url = URL(string: domainAPI + queryPercentEncoded) {
    print(url)
}

答案 2 :(得分:1)

问题是您网址的查询部分中的竖线(|)。它们应该以{{1​​}}转义。

这是我如何构建自动转义查询部分的URL:

%7C

如果您使用的是Swift 3,var components = NSURLComponents(string: "https://maps.googleapis.com/maps/api/staticmap")! components.query = "key=AIzaSyAJeHxZaZuNsYimNCJ4r0yuO-OYM8cINOI&center=6.241381,-75.595083&zoom=13&size=600x300&path=color:0x0000ff|weight:5|6.241381,-75.595083&signature=u7sM3m2h-qFSJoARR7cqD0CSBvU=" if let url = components.url { // ... } 将重命名为NSURLComponents

答案 3 :(得分:0)

(我没有使用基于密钥的身份验证,因此可能需要修改某些部分。)

首先,您需要一个没有签名的正确的百分比转义URL字符串:

let key = "AI...OI" // better hide your actual key in a public space...
let rawURLString = "https://maps.googleapis.com/maps/api/staticmap?key=\(key)&center=6.241381%2B-75.595083&zoom=13&size=600x300&path=color%3A0x0000ff%7Cweight%3A5%7C6.241381%2B-75.595083"
//`rawURLString` needs to be a valid string representation of URL.
assert(NSURL(string: rawURLString) != nil)

然后,为URL字符串生成base64编码的签名:

let encodedSignature: String = generateEncodedSignature(rawURLString, secret: yourSecretKey)

之后,您可以创建签名的URL字符串:

let signedURLString = "\(rawURLString)&signature=\(encodedSignature)"

(我相信你有一些功能可以在你的应用中生成签名或签名的网址,根据它修改上面的代码。)

signedURLString的内容应如下所示:

https://maps.googleapis.com/maps/api/staticmap?key=AI...OI&center=6.241381%2B-75.595083&zoom=13&size=600x300&path=color%3A0x0000ff%7Cweight%3A5%7C6.241381%2B-75.595083&&signature=u7...=

signature可能不以“u7”开头。)

使用NSURL创建signedURLString。不要删除百分比编码。

let url = NSURL(string: signedURLString)